可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.