1.react Data flow and communication between components
React is a top-down, one-way data stream, passed from the parent node to the child node (via props), and react re-renders all the child nodes if the top-level props changes.
Props: Used for the delivery of state between components, for passing data and configuration throughout the component tree, using This.props in the current component access props;
State refers to the internal status of the component, which can only be modified from the current component call This.setstate, and the general update subcomponent is updated by changing the value of the props and updating the new child component's value.
Component communication for parent-child components
Parent component passing data to child components
It can be achieved by passing props.
Class Parent extends react.component{
Constructor (props) {
super (props);
This.state = {
msg: ' Haha '
}
}
Componentdidmount () {
setTimeout () = {
This.setstate ({
msg: ' Xixi '
})
} (},1000)}
render () {
return (
<child msg = {this.state.msg}/ >
);
}
}
Class Child extends React.component {
Constructor (props) {
super (props);
}
Render () {
return <div>{this.props.msg}</div>
}
}
If there is more than one level between the child components of the parent component, then pass ... Passes information about the parent component to a further level of subcomponents. Subcomponents pass data to the parent component
The child component communicates to the parent component also needs to use props, the parent component passes a function to the child component, the child component calls the function.
Class Parent extends react.component{
Constructor (props) {
super (props);
This.state = {
msg: ' Haha '
}
}
passmsg (msg) {
this.setstate ({
msg:msg
})
}
Render () {
return <child passmsg = {msg = this.passmsg (msg)}/>
}
}
class Child extends react.component{
Constructor (props) {
super (props)
}
Componentdidmount () {
setTimeout ( = = {
this.props.passMsg (' Xixi ')
},1000)
}
render () {
return <div> subcomponent communicates to Parent component < /div>
}
}
Use the arrow function to pass the parent component's passmsg through props to the child component, primarily the arrow function ensures that when the child component calls the function, this inside the function still points to the parent component. For communication between sibling components
They have a common parent component, so 1 communicates to the parent component first, the parent component communicates to 2, and the communication between 1 and 2 is achieved.