How to pass data between child and parent in react-native?

匿名 (未验证) 提交于 2019-12-03 08:54:24

问题:

module.exports= class APP extends React.Component {   constructor(props){     super(props);     this.state = {       key1:'key1',       key2:'key2'     };   render() {     return (        <View>           <Button              onPress={this.goToTisch}>              1           </Button>           <Button              onPress={this.goToTisch}>              2           </Button>        </View>     );   } } 

I just write an app with react-native and do not know how to update the parent state from the child element. thank you in advance

回答1:

To call Parent's method from child, you can pass the reference like this.

Parent Class

<ChildClass     onRef={ref => (this.chilldmethod = ref)}     chilldmethod={this.parentMethod.bind(this)} />  parentMethod(data) {  } 

Child Class

let data = {     id: 'xyz',     name: 'zzz', };  this.props.childmethod(data); // This will call the method of parent 


回答2:

You need to pass from parent to child callback function, and then call it in the child.

For example:

class Parent extends React.Component {   constructor(props){     super(props);     this.state = {       show: false     };   }   updateState = () => {       this.setState({           show: !this.state.show       });   }   render() {     return (         <Child updateState={this.updateState} />     );   } }  class Child extends React.Component {   handleClick = () => {       this.props.updateState();   }   render() {     return (         <button onClick={this.handleClick}>Test</button>     );   } } 


回答3:

Like you do with React.

You have to exchange information through props, or use a library like Redux.



回答4:

Using Props like this:

Parent:

<Parent>   <Child onChange={this.change} /> </Parent> 

Child:

<button onclick={this.props.onChange('It Changed')} /> 

With this you can just do whatever you want in your parent.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!