如何为 ES6 class 创建一个 "field"(React 示例)

How to create a "field" for a ES6 class (React example)

我正在使用与 ES6 的反应,并希望在 class 级别重用一个变量。我收到一个错误:

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>
    );
  }
}

问题 我想在 class 中跨函数重用 tempUnits 变量。我该怎么做?

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

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 绑定到 this,例如 this.renderWeather.bind(this)

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

如果要更改 tempUnits,请使用;

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