[英]How to pass data between child and parent in react-native?
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. 我只是用react-native编写一个应用程序,并且不知道如何从子元素更新父状态。 thank you in advance
先感谢您
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>
);
}
}
To call Parent's method from child, you can pass the reference like this. 要从子级调用父级方法,您可以像这样传递引用。
Parent Class 家长班
<ChildClass
onRef={ref => (this.parentReference = ref)}
parentReference = {this.parentMethod.bind(this)}
/>
parentMethod(data) {
}
Child Class 儿童班
let data = {
id: 'xyz',
name: 'zzz',
};
//This will call the method of parent //这将调用parent的方法
this.props.parentReference(data);
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. 这样,您就可以在父母中做任何您想做的事情。
This can be achieved by two ways: 这可以通过两种方式实现:
Parent Component: 父组件:
//Needs argument
const addGoalHandler = goalTitle => {
// code for updating state
}
<GoalInput onAddGoal={this.addGoalHandler} />
Child Component: 子组件:
Way 1: Using Vanilla Javascript 方法1:使用香草Javascript
<Button
title="ADD"
onPress={props.onAddGoal.bind(this, enteredGoal)}
/>
Way 2: Using Arrow Function 方法2:使用箭头功能
<Button
title="ADD"
onPress={() => { props.onAddGoal(enteredGoal) } }
/>
class Parent extends Component{
constructor(props){
super(props);
this.state={value:''};
this.getData=this.getData.bind(this);
}
getData(val){
console.log(val);
this.setState({
value:val
});
}
render(){
const {value}=this.state
return(
<View>
<Screen sendData={this.getData}/>
<View>
<Text>
{this.state.value};
</Text>
</View>
</View>
)
}
}
export default Parent;
CHILD CLASS:
class Child extends Component{
componentWillMount(){
this.props.sendData('data');
}
render(){
return(
<View>
</View>
)
}
}
export default Child;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.