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

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

import React, { Component } from 'react';
// 子组件
class Content extends React.Component{
   render(){
       return 
{/* 点击时从父组件拿到最新值 渲染最新值 */}

{this.props.myDataProp}

} } // 父组件 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(
{/* 调用子组件,传入改变后的最新值 */}
); } } export default From5 ;

你可能感兴趣的:(从子组件中更新父组件的 state)