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

How to realize Cross-level component Communication by React

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces React how to achieve cross-level component communication, the article is very detailed, has a certain reference value, interested friends must read it!

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

These are all the contents of the article "how to achieve cross-level component communication in React". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

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: 253

*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