How to pass values between react native parent components and child components

How to pass values ​​between parent components and child components in react

To realize the two-way data flow between parent and child component communication in React Native, the idea is as follows:

1. The parent component passes props to the child component, which contains the initialization data of the child component and the callback method;

2. The child component manually triggers the callback method passed in by the parent function, and at the same time passes the data of the child component out.

PS. Use props
to pass events and implement them through callbacks. This implementation is not particularly good, but it is a simple implementation without any tools (redux)

The parent component passes the value to the child component: props
parent component:

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

Subassembly:

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


Subcomponents pass values ​​to parent components: use this.props in subcomponents...
in parent components:

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

Execute in a method of the subcomponent:

this.props.color('blue');

The error this.setState is not a function is reported.
The reason: this points to a problem. getModeText (val) {} This function gets the value returned by the child component, and what needs to be modified internally is the state of the parent component. At this time, this does not refer to the parent component, and this error will be reported

Solution:

  1. Add a binding when passing the function:
this.getModeText.bind(this)

Guess you like

Origin blog.csdn.net/Min_nna/article/details/126599101