从子组件中更新父组件的 state

2018-09-11  本文已影响17人  楠楠_c811

从子组件中更新父组件的 state 时 , 需要在父组件通过创建事件句柄 (handleChange) ,并作为 prop (updateStateProp) 传递到你的子组件上。实例如下:

import React, { Component } from 'react';
// 子组件
class Content extends React.Component{
   render(){
       return <div>
           {/* 点击时从父组件拿到最新值  渲染最新值 */}
           <button onClick={this.props.updateStateProp}>你来点我啊</button>
           <h4>{this.props.myDataProp}</h4>
       </div>
   }
}

// 父组件
class From5 extends Component {
   constructor(props){
       super(props);
       // 设置初始值
       this.state={
           value:'我是初始值'
       }
       // 绑定this
       this.handleChange = this.handleChange.bind(this)
   }
   // 改变value值事件
   handleChange(event){
       this.setState({value:'我被修改了哦'})
   }

  render(){
       // 为当前数据赋值   
      var value = this.state.value;
      return(
          <div>
               {/* 调用子组件,传入改变后的最新值 */}
              <Content myDataProp = {value}
                   updateStateProp={this.handleChange}
              />
          </div>
      );
  }

}
export default From5 ;
上一篇下一篇

猜你喜欢

热点阅读