如何为ES6类创建“字段”(反应示例)

时间:2018-11-08 12:07:28

标签: reactjs es6-class

我正在与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变量。我该怎么做?

2 个答案:

答案 0 :(得分:0)

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

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

完整代码:

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

答案 1 :(得分:0)

您应该将其添加到组件的状态中,而不是在构造方法中直接初始化该变量。在构造方法的下面添加以下代码段;

Sub LoopAndCopy
Dim ws as Worksheet
dim target as worksheet
set target = worksheets("target sheet name goes here") 'sheet you're copying to
For each ws in ThisWorkbook.worksheets  'loop through worksheets
    if ws.name <> target.name then   'if not the target sheet then...
         'copy your range into the next blank row in column A
         ws.range("your range here").copy target.range("A" & rows.count).end(xlup).offset(1,0)
     end if
next ws

您必须像state = { "tempUnits": "C", } 那样将功能this.renderWeather绑定到this

之后,您可以像this.renderWeather.bind(this)一样访问 tempUnit

如果要更改tempUnit,请使用;

this.state.tempUnits