


This article brings you common ways of communicating between React components that are simple and easy to use. One of the main contents of React knowledge is the communication between components. Here are several common ways of component communication, combined with examples, popular It's easy to understand. It is recommended to collect it. I hope it will be helpful to everyone.
1. Parent-child component communication
Principle: The parent component communicates with the child component through props (different from props in vue), and the child component Components communicate with parent components through callback events.
First, create a parent component Parent.js and a child component Children.js. The relationship between the two is a direct parent-child relationship.
Parent.js parent component is as follows. Give the parent component a default state, introduce the child component, and add toChildren={this.state.msg} to the child component, where props are 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:'父组件传递给子组件' }; this.changeMsg = this.changeMsg.bind(this) } changeMsg(){ this.setState({ msg:'父组件传递给子组件(改变之后的内容)' }) } render(){ return ( <p> </p><p>父子组件通信实例</p> <button>父传子</button> <children></children> ) } } export default Parent
Children.js sub-component is as follows. 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 //通过props拿到父组件传过来的值 }; } render(){ return ( <p> </p><p>从父组件传过来:</p> <span>{this.state.msg}</span> ) } } export default Children
Note: The value of the subcomponent should be consistent with the field props placed by the parent component in the subcomponent, that is, in this example toChildren, as follows
If the child component wants to pass the value to the parent component (upload the value), it can call the parent component The passed callback function
Add the callback function callback to Children.js in Parent.js, bind the changeMsg method
import React from 'react'; import Children from './Children'; class Parent extends React.Component { constructor(props) { super(props); this.state = { msg:'父组件传递给子组件', fromChildrn:'' }; this.changeMsg = this.changeMsg.bind(this) } changeMsg(val){ this.setState({ fromChildrn: val }) } render(){ return ( <p> </p><p>父子组件通信实例</p> <span>{this.state.fromChildrn}</span> <children></children> ) } } export default Parent
In the child component, use this.props.callback() Execute the callback function of the parent component to execute the binding method changeMsg and display 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('子组件传过来的值') //子组件通过此触发父组件的回调方法 } render(){ return ( <p> </p><p>从父组件传过来:</p> <span>{this.state.msg}</span> <button>子传父</button> ) } } export default Children
Note: The callback function names in props must be consistent, that is, in this example callback, as follows
##Summary: The above is Direct father and sonOne of the ways of component communication is from parent to child, through props; from child to parent, callbacks are executed.
2. Cross-level component communication Assume that there is a child component in a parent component, and there is a child component in this child component, which is temporarily called a "grandchild component". When the parent component needs When communicating with "grandchild components", there are two commonly used methods, layer-by-layer value passing and cross-layer value passing. 1. Passing values layer by layerThis method is based on the direct parent-child communication above and adds an intermediate layer. For example, if the parent and "grandson" components communicate, you can first communicate with the father and son, and then communicate with the child and "grandson". The transmission level becomes parent-->child-->"grandson". In the same way, props are passed down. Upload through callback. If you are interested, you can implement it yourself.2. Cross-level value transfer
As the name suggests, the parent communicates with the "grandson" without going through the child (middle layer) component. This leads toContext.
React official documentation explains Context:In a typical React application, data is passed from top to bottom (from parent to child) through the props attribute Yes, but this approach is extremely cumbersome for certain types of properties (e.g. locale preferences, UI themes) that are required by many components in the application. Context provides a way to share such values between components without having to explicitly pass props through each level of the component tree.
One sentence summary is:Cross-level value transfer, state sharing.
Look at a simple example and explain the usage directly. First, I create a context.js file (in the same directory as the parent and descendants), with the default value being an object.import React from "react"; const MyContext = React.createContext({text:'luck'}); export default MyContextThen, 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); } // 使用一个 Provider 来将当前的 value 传递给以下的组件树。 // 无论多深,任何组件都能读取这个值。 render(){ return ( <p> </p><p>context通信实例</p> <mycontext.provider> <children></children> </mycontext.provider> ) } } export default ParentThe sub-component is the middle layer and is not processed. It is used to wrap the "grandson" component.
import React from 'react'; import Grandson from './Grandson'; class Children extends React.Component { render(){ return ( <p> <grandson></grandson> </p> ) } } export default ChildrenTo add a "grandson" component, you also need to introduce context and add
static contextType = MyContext inside the component. At this time, you will be able to directly obtain the closest upper layer through this.context. The value passed by Provider, at this time this.context = {text:good luck}, that is, the parent component passes value.
import React from 'react'; import MyContext from './context'; class Grandson extends React.Component { static contextType = MyContext render(){ return ( <p> </p><p>通过context传过来:</p> <span>{this.context.text}</span> ) } } export default GrandsonGet the passed value through this.context.text.
## The above is a parent-->grandson process, that is, a downward process. If you want to upload a value from the grandson-->parent to the parent, you can use the callback Way
对父组件进行传值修改,在传过来的对象中添加一个属性,里面绑定父组件的方法value={{text:'good luck',toParent:this.fromGranson}}
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 }) } // 使用一个 Provider 来将当前的 theme 传递给以下的组件树。 // 无论多深,任何组件都能读取这个值。 render(){ return ( <p> </p><p>context通信实例</p> <span>{this.state.msg}</span> <mycontext.provider> <children></children> </mycontext.provider> ) } } export default Parent
然后在孙组件中添加一个按钮,绑定方法,执行函数回调
toParent(){
this.context.toParent('孙组件向父组件传数据')
}
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('孙组件向父组件传数据') } render(){ return ( <p> </p><p>通过context传过来:</p> <span>{this.context.text}</span> <p><button>context向上</button></p> ) } } export default Grandson
默认的页面为:
点击按钮之后,执行context中的回调,向上传值。
不管层级有多深,都可以使用context进行向下或向上传值。
注意:在下层组件中取的context中的字段需与value中传递字段保持一致。text与toParent
以上就是Context的大致使用,更多细节请往React官方文档:
Context – React=https://react.docschina.org/docs/context.html
三、兄弟(无嵌套)组件通信
当两个组件互不嵌套,处在同个层级或者不同层级上,他们之间要进行通信,有以下几种常用方法
1、某个组件先将值传到同一个父组件,然后在通过父组件传给另外一个组件,用到父子组件传值
2、使用缓存sessionStorage、localStorage等
3、如果两个组件之间存在跳转,可以使用路由跳转传值,附上详细用法
React学习笔记 -- 组件通信之路由传参(react-router-dom)_前端菜小白leo的博客-CSDN博客
4、event(发布--订阅)
首先,安装event
npm install event -save
新建一个event.js
import { EventEmitter } from 'events'; export default new EventEmitter();
然后另两个组件处于同层级(不同个父组件或者不同层级都可以)
import React from 'react'; import Grandson from './Grandson'; import GrandsonOther from './GrandsonOther'; class Children extends React.Component { render(){ return ( <p> <grandson></grandson> <grandsonother></grandsonother> </p> ) } } export default Children
组件一,导入event,在componentDidMount阶段添加监听addListener(订阅),在componentWillUnmount移除监听removeListener,事件名称与组件二中emit一致。
import React from 'react'; import event from '../event'; class Grandson extends React.Component { constructor(props) { super(props); this.state = { msg:'' } } componentDidMount(){ event.addListener('eventMsg',val => { this.setState({ msg:val }) }) } componentWillUnmount(){ event.removeListener('eventMsg') } render(){ return ( <p> </p><p>组件一</p> <p>通过event传过来:</p> <span>{this.state.msg}</span> ) } } export default Grandson
组件二,导入event,按钮绑定方法,使用event.emit触发(发布)事件。
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('eventMsg','通过evnet传过来的值') } render(){ return ( <p> </p><p>组件二</p> <span>{this.state.msg}</span> <p><button>event传值</button></p> ) } } export default Grandson
点击按钮,组件二发布事件,组件一监听(订阅)事件,更新内容。(如果交换发布者订阅者身份,写法一致)
注意:如果两个组件使用event进行通信,确保发布订阅的事件名称一致,如上例中 eventMsg
小结: event的方式比较灵活,不管是父子、跨级、还是同级,甚至毫无关联的组件,都可以使用此方式进行通信。
四、路由传值
React学习笔记 -- 组件通信之路由传参(react-router-dom)_前端菜小白leo的博客-CSDN博客
五、Redux
Redux基本用法(在react中使用,链路打通)_前端菜小白leo的博客-CSDN博客
总结:主要讲了react中常用的组件通信方式,在平时工作中,根据不同的应用场景,选择不同的通信方式,会让通信流程更加简单、清晰。
对比Vue中的组件通信方式,你会发现很多相似之处:
Vue组件间的通信方式(多种场景,通俗易懂,建议收藏)_前端菜小白leo的博客-CSDN博客
推荐学习:《react视频教程》
The above is the detailed content of Simple common techniques for communication between React components (organized and shared). For more information, please follow other related articles on the PHP Chinese website!

在react中,canvas用于绘制各种图表、动画等;可以利用“react-konva”插件使用canvas,该插件是一个canvas第三方库,用于使用React操作canvas绘制复杂的画布图形,并提供了元素的事件机制和拖放操作的支持。

React不是双向数据流,而是单向数据流。单向数据流是指数据在某个节点被改动后,只会影响一个方向上的其他节点;React中的表现就是数据主要通过props从父节点传递到子节点,若父级的某个props改变了,React会重渲染所有子节点。

在react中,antd是基于Ant Design的React UI组件库,主要用于研发企业级中后台产品;dva是一个基于redux和“redux-saga”的数据流方案,内置了“react-router”和fetch,可理解为应用框架。

因为在react中需要利用到webpack,而webpack依赖nodejs;webpack是一个模块打包机,在执行打包压缩的时候是依赖nodejs的,没有nodejs就不能使用webpack,所以react需要使用nodejs。

react是组件化开发;组件化是React的核心思想,可以开发出一个个独立可复用的小组件来构造应用,任何的应用都会被抽象成一颗组件树,组件化开发也就是将一个页面拆分成一个个小的功能模块,每个功能完成自己这部分独立功能。

react和reactdom的区别是:ReactDom只做和浏览器或DOM相关的操作,例如“ReactDOM.findDOMNode()”操作;而react负责除浏览器和DOM以外的相关操作,ReactDom是React的一部分。

在react中,forceupdate()用于强制使组件跳过shouldComponentUpdate(),直接调用render(),可以触发组件的正常生命周期方法,语法为“component.forceUpdate(callback)”。

react中没有双向绑定;react的设计思想就是单向数据流,没有双向绑定的概念;react是view层,单项数据流只能由父组件通过props将数据传递给子组件,满足了view层渲染的要求并且更易测试与控制,所以在react中没有双向绑定。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),