react中的状态提升(子组件给父组件传值、多个子组件状态共享)

官方对这个状态提升的解释是:

在 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>
    );
  }
}

我将官方的例子简化了,只展示了一个子组件如何将状态提升,实际操作中,肯定会有多个子组件进行状态共享,都一样的,状态已经提升到父组件了,那进行计算,可以传给多个子组件,这多个子组件也可将修改后的值通过事件传参给父组件,从而实现状态提升,多个子组件状态共享。

其实也是子组件给父组件传参

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值