首页 > 解决方案 > React:对象未定义 no-undef

问题描述

我制作了组件TempCalculator,它将计算水是否会在给定温度下沸腾。此外,它为当前输入值呈现 BoilingVerdict。


const BoilingPeek = (props) => {
  return props.celsius >= 100 ? (
    <p>Water would boil.</p>
  ) : (
    <p>Water is would not boil.</p>
  );
};

class TempCalculator extends React.Component {
  constructor(props) {
    super(props);
    this.handleTempChange = this.handleTempChange.bind(this);
    this.state = {
      temperature: "",
    };
  }

  handleTempChange(event) {
    this.setState({ temperature: event.target.name });
  }

  render() {
    return (
      <fieldset>
        <legend>Temprature of water in celsius</legend>
        <input name={temperature} onChange={this.handleTempChange} />
        <BoilingPeek celsius={parseFloat(temperature)} />
      </fieldset>
    );
  }
}
ReactDOM.render(<TempCalculator/>,document.getElementById("root"))

错误 'temperature' is not defined no-undef

标签: javascriptreactjsruntime-error

解决方案


那是因为temperature是一个状态。像这样使用:

<input name={this.state.temperature} onChange={this.handleTempChange} />
<BoilingPeek celsius={parseFloat(this.state.temperature)} />

推荐阅读