Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the methods of communication between React components

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article will share with you about the methods of communication between React components. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Communication between parent and child components

Principle: the parent component communicates with the child component through props (distinguished from the props in vue), and the child component communicates with the parent component through callback events.

First, create a parent component Parent.js and a child component Children.js, whose relationship is a direct parent-child relationship.

The Parent.js parent component is as follows, give the parent component a default state state, and import the child component. By adding toChildren= {this.state.msg} to the child component, the props is passed to the child component.

Import React from 'react';import {Button} from' element-react';import Children from'. / Children'; class Parent extends React.Component {constructor (props) {super (props); this.state = {msg:' parent component passes to child component'} This.changeMsg = this.changeMsg.bind (this)} changeMsg () {this.setState ({msg:' parent component passes to child component (changed content)'})} render () {return (

Parent-child component communication instance

Father to son)}} export default Parent

The Children. js child component is as follows, and the initial state gets the value passed by the parent component through props.

Import React from 'react'; class Children extends React.Component {constructor (props) {super (props); this.state = {msg:this.props.toChildren / / get the value passed by the parent component via props};} render () {return (

Passed from the parent component:

{this.state.msg})}} export default Children

Note: the value of the child component should be the same as the field props that the parent component puts in the child component, that is, the toChildren in this example, as follows

If the child component wants to pass a value to the parent component (upwards), it can call the callback function passed by the parent component

Add the callback function callback to Children.js in Parent.js and bind the changeMsg method

Import React from 'react';import Children from'. / Children'; class Parent extends React.Component {constructor (props) {super (props); this.state = {msg:' parent component passes to child component', fromChildrn:''}; this.changeMsg = this.changeMsg.bind (this)} changeMsg (val) {this.setState ({fromChildrn: val})} render () {return ()

Parent-child component communication instance

{this.state.fromChildrn})}} export default Parent

In the child component, the callback function of the parent component is executed with this.props.callback (), which executes the binding method changeMsg, which displays the value passed by the child component

Import React from 'react';import {Button} from' element-react'; class Children extends React.Component {constructor (props) {super (props); this.state = {msg:this.props.toChildren} This.toParent = this.toParent.bind (this)} toParent () {this.props.callback ('value passed by the child component') / the callback method of the parent component triggered by the child component} render () {return (

Passed from the parent component:

{this.state.msg} child to parent)}} export default Children

Note: the name of the callback function in props should be the same, that is, callback in this example, as follows

Summary: the above is one of the ways for direct parent-child components to communicate. The parent passes from the parent to the child, passes the parent through the props; child, and performs callback.

Second, cross-level component communication

Suppose there is a child component in a parent component, and there is another child component in the child component, temporarily called the "grandchild component". When the parent component needs to communicate with the "grandchild component", there are two common ways to pass values layer by layer and across layers.

1. Pass the value layer by layer

This way is to add an intermediate layer to the above direct parent-son communication. For example, the communication between father and "grandson" components can be communicated first by father and son, and then by son "grandson". The level of transmission becomes father-> son-- > "grandson". In the same way, it is passed down through props and uploaded through callback. Do not unfold, if you are interested, do it yourself.

2. Cross-stage value transfer

As the name implies, the father communicates with the "grandson" without going through the child (middle tier) components. This leads to Context.

The official React documentation explains Context:

In a typical React application, data is passed from top to bottom (parent and child) through props attributes, but this is extremely cumbersome for some types of attributes (for example, regional preferences, UI themes), which are required by many components in the application. Context provides a way to share such values between components without explicitly passing props layer by layer through the component tree.

It can be summed up in a word: cross-level value transfer and state sharing.

Take a look at a simple example and talk about usage directly.

First, I create a context.js file (in the same directory as the parent and grandchild), with a default value of an object.

Import React from "react"; const MyContext = React.createContext ({text:'luck'}); export default MyContext

Then, rewrite the parent component, introduce context, and use a Provider to pass the current value to the following component tree, where value is the passed value.

Import React from 'react';import Children from'. / Children';import MyContext from'. / context'; class Parent extends React.Component {constructor (props) {super (props);} / uses a Provider to pass the current value to the following component tree. / / any component can read this value no matter how deep it is. Render () {return (

Context communication instance

)} export default Parent

The sub-component is the middle layer, does not do the processing, and is used to wrap the "grandson" component.

Import React from 'react';import Grandson from'. / Grandson'; class Children extends React.Component {render () {return ()}} export default Children

To add a "grandchild" component, you also need to introduce context and add static contextType = MyContext inside the component. In this case, the value passed by the nearest Provider in the upper layer can be directly obtained through this.context. In this case, this.context = {text:good luck}, that is, the parent component passes the value.

Import React from 'react';import MyContext from'. / context'; class Grandson extends React.Component {static contextType = MyContext render () {return (

Sent through context:

{this.context.text})}} export default Grandson

Get the passed value through this.context.text.

The above is a process of father-> grandson, that is, the downward process. If you want grandson-> father to pass the value up, you can do so by callback.

Modify the value of the parent component by adding a property to the passed object in which the method value= {{text:'good luck',toParent:this.fromGranson}} of the parent component is bound

Import React from 'react';import Children from'. / Children';import MyContext from'. / context'; class Parent extends React.Component {constructor (props) {super (props); this.state = {msg:''}; this.fromGranson = this.fromGranson.bind (this)} fromGranson (val) {this.setState ({msg:val})} / / uses a Provider to pass the current theme to the following component tree. / / any component can read this value no matter how deep it is. Render () {return (

Context communication instance

{this.state.msg})}} export default Parent

Then add a button to the grandson component, bind the method, and execute the function callback

ToParent () {this.context.toParent ('grandchild component passes data to parent component')} import React from 'react';import MyContext from'. / context';import {Button} from 'element-react' class Grandson extends React.Component {static contextType = MyContext constructor (props) {super (props) This.toParent = this.toParent.bind (this)} toParent () {this.context.toParent ('grandchild component passes data to parent component')} render () {return (

Sent through context:

{this.context.text} context up)}} export default Grandson

The default page is:

After clicking the button, execute the callback in context and pass the value up.

No matter how deep the level is, you can use context to pass values down or up.

Note: the fields in the context taken from the lower-level components should be consistent with the passed fields in the value. Text and toParent

The above is the general use of Context. For more details, please refer to the React official documentation:

Context-React

III. Communication between brothers (without nesting) components

When two components are not nested and are at the same or different levels, there are several common ways for them to communicate with each other

1. A component first passes the value to the same parent component, and then passes it to another component through the parent component, using the parent and child components to pass the value

2. Use cache sessionStorage, localStorage, etc.

3. If there is a jump between the two components, you can use the route jump to pass the value, with detailed usage attached

React Learning Notes-- component Communication routing parameters (react-router-dom) _ front-end vegetable rookie leo's blog-CSDN blog

4. Event (publish-subscribe)

First, install event

Npm install event-save

Create a new event.js

Import {EventEmitter} from 'events';export default new EventEmitter ()

Then the other two components are at the same level (different parent components or different levels are fine)

Import React from 'react';import Grandson from'. / Grandson';import GrandsonOther from'. / GrandsonOther'; class Children extends React.Component {render () {return ()} export default Children

Component 1, import event, add listening addListener (subscription) in componentDidMount phase, remove listening removeListener in componentWillUnmount, and the event name is the same as emit in component 2.

Import React from 'react';import event from'. / event';import {Button} from 'element-react' class Grandson extends React.Component {constructor (props) {super (props); this.state = {msg:''} this.toOther = this.toOther.bind (this)} toOther () {event.emit (' value passed by eventMsg',' through evnet')} render () {return (

Component two

{this.state.msg} event value)}} export default Grandson

Component 2, import event, button binding method, use event.emit to trigger (publish) events.

Import React from 'react';import event from'. / event';import {Button} from 'element-react' class Grandson extends React.Component {constructor (props) {super (props); this.state = {msg:''} this.toOther = this.toOther.bind (this)} toOther () {event.emit (' value passed by eventMsg',' through evnet')} render () {return (

Component two

{this.state.msg} event value)}} export default Grandson

Click the button, component 2 release event, component 1 monitor (subscribe) event, update content. (if the identity of the publisher and subscriber is exchanged, the writing is the same)

Note: if the two components communicate using event, make sure that the event names of the publish and subscribe are the same, such as eventMsg in the example above

Summary: the event approach is flexible, and it can be used to communicate with parent-child, cross-level, peer, or even unrelated components.

Thank you for reading! This is the end of this article on "what are the methods of communication between React components?". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report