官方对这个状态提升的解释是:
在 React 中,将多个组件中需要共享的 state 向上移动到它们的最近共同父组件中,便可实现共享 state。这就是所谓的“状态提升”。
看看官方文档给出的例子:
// 这是子组件
class TemperatureInput extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) { // input change后的值
this.props.onTemperatureChange(e.target.value); // input的值当参数传入父组件传入的事件
}
render() {
const temperature = this.props.temperature; // 接受父组件传过来的经过计算的input的值
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.state = {temperature: ''};
}
handleCelsiusChange(temperature) { // 接受子组件传过来的input值
this.setState({ temperature});
}
render() {
const temperature = this.state.temperature;
const celsius = temperature*20; // 将子组件传入的值进行计算
return (
<div>
<TemperatureInput
temperature={celsius} // 计算后的值传给子组件
onTemperatureChange={this.handleCelsiusChange} // 将事件传给子组件,去接受子组件传入的input值
/>
<BoilingVerdict
celsius={parseFloat(celsius)} />
</div>
);
}
}
我将官方的例子简化了,只展示了一个子组件如何将状态提升,实际操作中,肯定会有多个子组件进行状态共享,都一样的,状态已经提升到父组件了,那进行计算,可以传给多个子组件,这多个子组件也可将修改后的值通过事件传参给父组件,从而实现状态提升,多个子组件状态共享。
其实也是子组件给父组件传参