我在理解概念時遇到了問題。我想從renderWeather()內部傳遞windColor變量到render()和函數alertKitesurf我應該使用this.state和setState,或者我可以用變量來完成它嗎?React類如何在同一文件中的所有方法中傳遞變量
我的代碼不起作用。
PS。爲什麼在課堂外你需要添加函數method(),而在類的括號內卻不需要?
import React, ....
class WeatherList extends Component { constructor(props) {
super(props);
this.fixit = 'blue'; } // render single city
renderWeather(cityData) {
const lol = this;
const name = cityData.city.name;
const temp = cityData.list.map(weather => (weather.main.temp - 272));
const humi = cityData.list.map(weather => weather.main.humidity);
const wind = cityData.list.map(weather => weather.wind.speed);
// Kitesurf alert!
console.log(lol.fixit);
const windColor = alertKitesurf(wind);
lol.fixit = windColor;
return (
<tr key={name}>
<td className="col-md-3">{name}</td>
<Chart data={temp} color="blue" />
<Chart data={humi} color="blue" />
<Chart data={wind} color={windColor} />
</tr>
); }
render() {
let fixdiv;
if (this.fixit === 'blue') {
fixdiv = <div>test</div>;
}
else {
fixdiv = <div>OMG</div>;
}
return (
<div>
<table className="table table-hover">
<thead>
<tr>
<th className="col-md-3">City</th>
<th className="col-md-3">Temperature</th>
<th className="col-md-3">Humidity</th>
<th className="col-md-3">Wind Speed</th>
</tr>
</thead>
<tbody>
{this.props.weather.map(this.renderWeather)}
</tbody>
</table>
{fixdiv}
</div>
); } } // function(state) -> function({weather}) -> weather : weather -> weather function mapStateToProps({ weather }) { return { weather }; }
function alertKitesurf(wind) { let color = 'blue'; for (let windspeed of wind) {
if (windspeed > 7) {
color = 'red';
} } if (color === 'red') {
alert("WIND SPOTTED! (14+knots) LETS GO KITSURF!"); } return color; }
export default connect(mapStateToProps)(WeatherList);
可以格式化代碼? – udnisap
您可以在變量之前使用'this'關鍵字使其成爲全局特定的類。如果你的變量正在改變渲染函數,那麼你應該把它放在狀態中,並用setState方法改變它的值。 –