'How to change state of child component in react native?
I have a parent component like this:
class Parent extends Component {
onChangeState=()=>{
//I want to change it here
}
render(){
return(
<child />)
})
}
I want to change child component's state in parent. How can I do that ?
class Child extends Component {
constructor(props) {
super(props);
this.state = {
item: ''
};
}
}
Solution 1:[1]
In this case, you need to define the state in the parent and pass it as a prop to the child. Then, your parent has full control over the state and a state change will cause a rerender of the child and its prop will be updated. This yields in the same effect.
class Parent extends Component {
constructor(props) {
super(props);
this.state = { item: '' };
}
onChangeState = (newItem) => {
this.setState({ item: newItem })
}
return (
<Child state={this.state} />
)
}
class Child extends Component {
constructor(props) {
super(props)
}
render() {
return (
<Text>{this.props.state.item}</Text>
)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | David Scholz |