我正在阅读 ReactJS 文档中关于"Lifting State Up"的内容,有些不是很清楚。这里可以找到代码片段:https://codepen.io/valscion/pen/jBNjja?editors=0010
在 TemperatureInput 组件中,onTemperatureChange 事件处理程序调用 handleCelsiusChange,但后者包含一个名为 temperature 的参数。我们如何传递这个参数?在 onTemperatureChange 中没有传递任何参数。我缺少了什么?
希望有人能帮助我理解这个问题。
希望有人能帮助我理解这个问题。
class TemperatureInput extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.props.onTemperatureChange(e.target.value);
}
render() {
const temperature = this.props.temperature;
const scale = this.props.scale;
return (
<fieldset>
<legend>Enter temperature in {scaleNames[scale]}:</legend>
<input value={temperature}
onChange={this.handleChange} />
</fieldset>
);
}
}
class Calculator extends React.Component {
constructor(props) {
super(props);
this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
this.state = {temperature: '', scale: 'c'};
}
handleCelsiusChange(temperature) {
this.setState({scale: 'c', temperature});
}
handleFahrenheitChange(temperature) {
this.setState({scale: 'f', temperature});
}
render() {
const scale = this.state.scale;
const temperature = this.state.temperature;
const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;
return (
<div>
<TemperatureInput
scale="c"
temperature={celsius}
onTemperatureChange={this.handleCelsiusChange} />
<TemperatureInput
scale="f"
temperature={fahrenheit}
onTemperatureChange={this.handleFahrenheitChange} />
<BoilingVerdict
celsius={parseFloat(celsius)} />
</div>
);
}
}
TemperatureInput
组件的代码,我可以看到您在onTemperatureChange
中传递了什么,这样会更好。 - Ritesh Bansal