美文网首页
从子组件中更新父组件的 state

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

作者: 楠楠_c811 | 来源:发表于2018-09-11 12:06 被阅读17次

    从子组件中更新父组件的 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 ;
    

    相关文章

      网友评论

          本文标题:从子组件中更新父组件的 state

          本文链接:https://www.haomeiwen.com/subject/yctugftx.html