如何创建一个";字段";对于ES6类(React示例)



我正在使用react with ES6,并希望在类级别重用一个变量。我得到一个错误:

bundle.js:29225 Uncaught TypeError: Cannot read property 'tempUnits' of undefined

我的代码在这里

class WeatherList extends Component {
constructor(){
super();
this.tempUnits = 'C'; // <== initialise it here
}

renderWeather(cityData) {
console.log('tempunits', this.tempUnits); // <== blows up here
const name = cityData.city.name;
const temps = _.map(cityData.list.map(weather => weather.main.temp), (temp) => temp-273);
const pressures = cityData.list.map(weather => weather.main.pressure);
const humidities = cityData.list.map(weather => weather.main.humidity);
const { lon, lat } = cityData.city.coord;
return (
<tr key={name}>
{/* <td><GoogleMap lon={lon} lat={lat} /></td> */}
{/* <== Use it here */}
<td><Chart data={temps} color="orange" units="{this.tempUnits}" /></td>
<td><Chart data={pressures} color="green" units="hPa" /></td>
<td><Chart data={humidities} color="black" units="%" /></td>
</tr>
);
}
render() {
return (
<table className="table table-hover">
<thead>
<tr>
<th>City</th>
{/* <== Reuse it here again */}
<th>Temperature ({this.tempUnits})</th>
<th>Pressure (hPa)</th>
<th>Humidity (%)</th>
</tr>
</thead>
<tbody>
{this.props.weather.map(this.renderWeather)}
</tbody>
</table>
);
}
}

问题我想在类中的函数之间重用tempUnits变量。我该怎么做?

添加以下行。它将用一个新实例替换renderWeather函数,该实例将绑定到类级上下文。

this.renderWeather = this.renderWeather.bind(this);

完整代码:

class WeatherList extends Component {
constructor(){
super();
this.tempUnits = 'C';
this.renderWeather = this.renderWeather.bind(this);
}

与其在构造函数方法中直接初始化变量,不如将其添加到组件的状态中。在构造函数方法下面添加以下代码段;

state = {
"tempUnits": "C",
}

您必须像this.renderWeather.bind(this)一样将函数this.renderWeather绑定到this

之后,您可以像this.state.tempUnits一样访问tempUnit

如果要更改tempUnits,请使用;

this.setState({ tempUnits: "F" }); 

最新更新