개념을 이해하는 데 문제가 있습니다. renderWeather() 내부에서 render() 및 function alertKitesurf에 windColor 변수를 전달하려고합니다.React Class 동일한 파일의 모든 메소드에서 변수를 전달하는 방법
this.state와 setState를 사용해야하며 그렇지 않으면 변수를 사용할 수 있습니까?
내 코드가 작동하지 않습니다.
추신. 클래스 외부에서 왜 필요없는 클래스의 괄호 안에 function 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' 키워드를 사용하여 특정 클래스에 대한 전역 변수로 만들 수 있습니다. 당신의 변수가 render 함수를 바꾸고 있다면, 이것을 상태에 넣고 setState 메소드를 사용하여 값을 변경해야합니다. –