react native 父组件与子组件之间如何相互传值

react 中父组件与子组件之间如何相互传值

实现React Native 中父子组件通信间的双向数据流,思路如下:

1.父组件向子组件传递props,其中props 中带有子组件的初始化数据以及回调方法;

2.子组件手动触发父函数传递进来的回调方法,同时将子组件的数据传递出去。

PS.使用 props
来传递事件,并通过回调的方式实现,这样的实现其实不是特别好,但在没有任何工具(redux)的情况下不失为一种简单的实现方式

父组件给子组件传值:props
父组件:

<View>
  <AutoComponent navigate={
    
    this.props.navigation.navigate} />
</View>

子组件:

<RkButton rkType='rounded'
  onPress={
    
    () =>{
    
    
      this.props.navigate('ModeList')
  }
}>模式管理</RkButton>


子组件向父组件传值:子组件里使用this.props…
父组件里:

constructor() {
    
    
	super();
	this.state = {
    
    
	        title:'标题'
	    };
};
render() {
    
    
	return (
    <View>
      <AutoComponent modeText={
    
    this.getModeText.bind(this)} />//要写this指向,不然会报错
    </View>
	);
};
getModeText(text){
    
    
//父组件接收text值
    this.setState({
    
    
      title:text
    });
  }

子组件某个方法里执行:

this.props.color('blue');

报错 this.setState is not a function
原因: this的指向问题。 getModeText (val) {}这个函数获取的是子组件返回的值,而内部需要修改的是 父组件的 state。 这时this 就指的不是父组件,就会报这个错误

解决办法:

  1. 传入函数时加一个绑定:
this.getModeText.bind(this)

猜你喜欢

转载自blog.csdn.net/Min_nna/article/details/126599101