【问题标题】:React: onChange not updating value to input field反应:onChange 不更新输入字段的值
【发布时间】:2017-12-06 21:33:53
【问题描述】:

我正在编写一个将温度从摄氏度转换为华氏度的页面。

用户在第一个输入字段中以摄氏度为单位给出温度, 那么 onChange 应该调用函数 convertCelciustoFahr。

convertCelciustoFahr 通过函数 this.setState() 改变 state.fahrenheit 并且华氏温度应该更新到第二个输入字段。

class App extends Component {

constructor(props){
  super(props);
  this.state = {
    //Temperature in fahrenheit
    fahrenheit: 0,
    //Temperature in celcius
    celcius: 0,
  };
  //Binding
  this.convertCelciustoFahr = this.convertCelciustoFahr.this;
}


//Converts celcius to fahrenheit
convertCelciustoFahr(event){
  var celcius = Number(event.target.value);
  this.setState( function(state,props){
    return{
      fahrenheit: (celcius-32)/(5/9),
    } 
  }
  )
}

render() {
  return (
    <div className="App">

    <h1>Celcius to Fahrenheit converter</h1>
    <form id="conversion">
      <input className="Celcius" placeholder="°C" onChange={this.convertCelciustoFahr} />
      <p>=</p>
      <input className="Fahrenheit" value={this.state.fahrenheit} placeholder="°F" />

    </form>
  </div>
  );
}
}


export default App;

这里是html:

<body>
<noscript>
  You need to enable JavaScript to run this app.
</noscript>
<div id="root">
<div data-reactroot="" class="App">
  <h1>Celcius to Fahrenheit     converter</h1>
  <form id="conversion">
    <input class="Celcius" placeholder="°C">
    <p>=</p>
    <input class="Fahrenheit" value="0" placeholder="°F">
  </form>
</div>
</div>

好像没有启用Javascript,也没有触发onChange事件。

为什么 onChange 不更新华氏输入字段的值?

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

使用绑定

 this.convertCelciustoFahr = this.convertCelciustoFahr.bind(this);

【讨论】:

  • -1 因为“您可以使用箭头函数,因为它会自动绑定到此”是错误的。箭头函数不会“绑定”,因为它们没有 this
  • 嗨@Chris 是的,你是对的,我没有解释正确,所以我更新了我的答案:) 它应该是箭头函数绑定到他们当前上下文的词汇 this
猜你喜欢
  • 2018-07-16
  • 1970-01-01
  • 2016-10-13
  • 2020-07-19
  • 1970-01-01
  • 2016-12-20
  • 1970-01-01
  • 1970-01-01
  • 2020-12-28
相关资源
最近更新 更多