React Native 子组件修改父组件的State

React Native 子组件传递State给父组件

一.原理

React本身是单向数据流,父组件可以传递props给子组件。
那么假如要实现React / ReactNative 中父子组件通讯间的双向数据流,思路可以是在这样:

  1. 父组件向子组件传递props,其中props中带有子组件的初始化数据以及回调方法
  2. 子组件手动触发父函数传递进来的回调方法,同时时将子组件的数据传递回去
    这里写图片描述
    PS.使用 props 来传递事件,并通过回调的方式实现,这样的实现其实不是特别好,但在没有任何工具(redux)的情况下不失为一种简单的实现方式

二.代码演示

ReactNative@0.56,使用ES6语法,优先使用箭头函数

父组件

export default class Parent extends Component{
    //初始状态
    constructor(props) {
        super(props);
        this.state = {
          stateName:'parent',
        };
    };
    //回调函数:将传来的参数用this.setState方法修改初始状态值
    updateState (data) {              //这个data是个参数
        this.setState(data);
    }
    render(){
        return <Child   
                stateName={this.state.stateName}  //将父组件的stateName传给子组件
                updateParentState={this.updateState.bind(this)} //绑定父组件的updateState方法中的this
                />
    }
}

子组件|Es6

    const Child =(props)=>{
        const {stateName} = props; //即stateName=props.stateName,取出传递进来的props中的stateName 
        //
        setParentState=(data)=>{
            props.updateParentState(data);
        }
        return(
            <View>
                <Text 
                    //这里要注意的是,返回的参数必须是一个对象,所以要用{}括起来,而不是括号()
                    onPress={() => {this.setParentState(  {stateName: 'child'}  )} }
                >我的状态是{stateName}</Text>
            </View>
        )
    }

三.附录

猜你喜欢

转载自blog.csdn.net/m0_38021769/article/details/81839699
今日推荐