React component value transfer is a very important topic when using React. Component value transfer includes parent component value transfer and sibling component value transfer.
The parent component passes values to the child components through props// In the parent component
<ChildComponent data={[1.2.3]} / >// In the child componentGet the data from the parent component via propsconsole.log(this.props.data);
Copy the code
Child components pass values to parent components// The child passes a getData method to the props and passes the parameter data to the parent
export default class ChildComponent extend compenent{
state={
data: [1.2.3]}render(){
const {data}=this.state;
return(< div > subcomponents < button onClick = {() = > {this. Props. GetData (data)}} > < button > < / div >)}}Copy the code
The parent component gets the value passed by the child component// The parent component receives a getData method through props to get the value of the child component
import Child from './Child.js';export default class Parent extend compenent{
getData=(data) = >{
console.log(data);
}
render(){
return (
<div>The parent component<ChildComponent getData={this.getData}/>
</div>)}}Copy the code
Sibling components pass values// We usually use publish/subscribe mode, of course, through the parent component for the transfer, but publish/subscribe mode is better
import PubSub from 'pubsub-js' // Add the library to the component
// Publish messages -sendMessage is the method name, used when subscribing
PubSub.publish("sendMessage", {'News is out.'.num:20})
// Subscribe messages - Get data by subscribing to the sendMessage method
componentDidMount(){
let mySub = PubSub.subscribe("sendMessage".(msg,data) = >{
console.log(msg,data)
})
}
Copy the code
In fact, the idea of component transfer value should be almost the same, we have an impression, easy to find information later, you learn waste