Reputation: 173
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
Upvotes: 15
Views: 39208
Reputation: 821
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
<Button
title="ADD"
onPress={props.onAddGoal.bind(this, enteredGoal)}
/>
Way 2: Using Arrow Function
<Button
title="ADD"
onPress={() => { props.onAddGoal(enteredGoal) } }
/>
Upvotes: 1
Reputation: 1
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;
Upvotes: -1
Reputation: 1539
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
this.props.parentReference(data);
Upvotes: 14
Reputation: 2709
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>
);
}
}
Upvotes: 24
Reputation: 1681
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.
Upvotes: 4
Reputation: 32767
Like you do with React.
You have to exchange information through props, or use a library like Redux.
Upvotes: 4