In the process of using react, there is an unavoidable need for message passing (communication) between components, and communication between components generally has the following situations:
1 The parent component communicates to the child component
2 subcomponents communicating to parent components
Parent component communicates to child components
This is the simplest and most commonly used form of communication: The parent component passes the props to the subassembly, and the subassembly is props after the child component is processed accordingly.
Here is the demo code:
Parent Component App.js:
Import react,{Component} from "React";
Import Sub from "./subcomponent.js";
Import "./app.css";
Export default class APP extends component{
render () {return
(
<div>
<sub title = "No Gifts for the holidays this year"/ >
</div>
)
}
}
Sub-component Subcomponent.js:
Import react from "react";
Const SUB = (props) => {return
(
Child components communicate to parent components
The callback function enables the child component to communicate to the parent component: The parent component passes a function as props to the subassembly, and the child component invokes the callback function to communicate to the parent component.
Here is the demo code:
Subcomponent.js:
Import react from "react";
Const SUB = (props) => {
Const CB = (msg) => {return
() => {
props.callback (msg)
}
}
ret Urn (
<div>
<button onClick = {CB ("We communicate put")}> click me </button>
</div>
)
}
Export default Sub;
App.js:
Import react,{Component} from "React";
Import Sub from "./subcomponent.js";
Import "./app.css";
Export default class APP extends component{
callback (msg) {
console.log (msg);
Render () {return
(
<div>
<sub callback = {This.callback.bind (this)}/>
</div>
)
}
}
Only two of these are currently used, and new updates are used later.