How Change State Or Property Of An Outer / Separate Component In Reactjs?
Solution 1:
The old fashioned way, which is fine for a small page, is to move all states into the root node (comp1
). Other components become stateless. The root node passes to its children the properties they want to render, alongside the setters required to mutate the properties. For instance, comp5
gets a property username
which is just the value of comp1.state.username
, plus a property setUsername
, which is a function taking a username
string parameter in which comp1
uses setState
to update its state's username
. This way comp5
can render and update the username, and other components are aware of the change (setState
triggers a render of children).
For more complex apps, passing all these properties to children gets tedious, and you can resort to framework like flux
and redux
.
Solution 2:
i think standard way of doing it is something like this
in your react component:
constructor(props) {
...
this.state = {selectedComp4: null
...
}
}
...
handleSelectedComp4Change (yourData) {
this.setState({selectedComp4: yourData})
}
...
render() {
...
return (
<comp1><div><comp2></comp2><comp3><comp4onSelectedComp4Change = {this.handleSelectedComp4Change}/><comp4onSelectedComp4Change = {this.handleSelectedComp4Change}/>
...
</comp3></div><comp5SelectedComp4={this.state.selectedComp4}></comp5></comp1>
)
}
in comp4 send your data: onClick={() => { this.props.onSelectedComp4Change(someData) }}
in comp5 use your data in this.props.SelectedComp4
EDIT:
just like @Valéry said
Post a Comment for "How Change State Or Property Of An Outer / Separate Component In Reactjs?"