子组件的状态发生了改变,如何向父组件汇报?示例
// 子组件
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;
return (
<fieldset>
<input value={temperature}
onChange={this.handleChange} />
</fieldset>
);
}
}
// 父组件
class Calculator extends React.Component {
constructor(props) {
super(props);
this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
this.state = {temperature: ''};
}
handleCelsiusChange(temperature) {
this.setState({temperature: temperature});
}
render() {
return (
<div>
<TemperatureInput
temperature={this.state.temperature}
onTemperatureChange={this.handleCelsiusChange} />
</div>
);
}
}
ReactDOM.render(
<Calculator />,
document.getElementById('root')
);