Current DOM tree is like:
<comp1>
<div>
<comp2></comp2>
<comp3>
<comp4 />
<comp4 />
.........
.........
.........
</comp3>
</div>
<comp5></comp5>
</comp1>
Component5 ie is my modal. I want to set it's state and props by onclick event on
My objective is to display the detail data on a modal based on the selection. So I need to set the state and props of modal component accordingly. How can I that in the current structure?
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
.
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>
<comp4 onSelectedComp4Change = {this.handleSelectedComp4Change}/>
<comp4 onSelectedComp4Change = {this.handleSelectedComp4Change}/>
...
</comp3>
</div>
<comp5 SelectedComp4={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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.