React中组件间通信的几种方式

组件间进行消息传递(通信)的几种方式,主要有一下几种:

  • 父组件向子组件通信
  • 子组件向父组件通信
  • 跨级组件之间通信
  • 非嵌套组件间通信

父组件向子组件通信

这是最简单也是最常用的一种通信方式:父组件通过向子组件传递 props,子组件得到 props 后进行相应的处理。

import React,{ Component } from 'react';
import Sub from './SubComponent.js';
import './App.css';

export default class App extends Component{
    render() {
        return(
            <div>
                <Sub title = '今年' />
            </div>
        )
    } 
}

子组件 SubComponent.js:

import React from 'react';

const Sub = (props) => {
    return(
        <h1>
            {props.title}
        </h1>
    )
}

export default Sub;

子组件向父组件通信

利用 回调函数,可以实现子组件向父组件通信:父组件将一个函数作为props传入子组件,子组件调用该回调函数,便可以向父组件通信。

子组件Subcomponent.js

import React from 'react';

const Sub = (props) => {
    const cb = (msg) => {
        return ()=> {
            props.callback(msg)
        }
    }

    return(
        <div>
            <button onClick={ cn('我们通信吧')}>点击我</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>
        )
    }
}

跨级组件通信

所谓跨级组件通信,就是父组件向子组件的子组件通信,向更深层的子组件通信。跨级组件通信可以采用下面两种方式:

  • 中间组件层层传递 props
  • 使用 context 对象

对于第一种方式,如果父组件结构较深,那么中间的每一层组件都要去传递 props,增加了复杂度,并且这些 props 并不是这些中间组件自己所需要的。不过这种方式也是可行的,当组件层次在三层以内可以采用这种方式,当组件嵌套过深时,采用这种方式就需要斟酌了。
使用 context 是另一种可行的方式,context 相当于一个全局变量,是一个大容器,我们可以把要通信的内容放在这个容器中,这样一来,不管嵌套有多深,都可以随意取用。
使用 context 也很简单,需要满足两个条件:

  • 上级组件要声明自己支持 context,并提供一个函数来返回相应的 context 对象
  • 子组件要声明自己需要使用 context

父组件 App.js

import React,{ Component } from "react";
import PropTypes from "prop-types";
import Sub from "./SubComponent.js";
import "./App.css";


export default class App extends Component{
    // 父组件声明自己支持 context
    static childContentTypes = {
        color: PropTypes.string,
        callback: PropTypes.func,
    }

    // 父组件提供一个函数,用来返回相应的 context 对象
    getChildContext() {
        return{
            color: 'red',
            callback: this.callback.bind(this)
        }
    }
    
    callback(msg){
        console.log(msg)
    }

    render(){
        return(
            <div>
                <Sub></Sub>
            </div>
        );
    }
}

子组件 Sub.js

import React from "react";
import SubSub from "./SubSub";

const Sub = (props) =>{
    return(
        <div>
            <SubSub />
        </div>
    );
}

export default Sub;

子组件的子组件SubSub.js:

import React,{ Component }  from "react";
import PropTypes from "prop-types";

export default class SubSub extends Component{
    //子组件声明自己需要使用 context
    static contextTypes = {
        color: PropTypes.string,
        callback: PropTypes.func,
    }
    
    render(){
        const style = { color: this.context.color }
        const cb = (msg) => {
            return () => {
                this.context.callback(msg);
            }
        }
        return(
            <div style = { style }>
                SUBSUB
                <button onClick = {cb('又回来了')}>惦记我<button/>
            </div>
        );
    }
}

如果是父组件向子组件单向通信,可以使用变量,如果子组件想向父组件通信,同样可以由父组件提供一个回调函数,供子组件调用,回传参数。

在使用 context 时,有两点需要注意:

  • 父组件需要声明自己支持context,并提供context中属性的PropTypes
  • 子组件需要声明自己需要使用context,并提供其组要使用的context属性的PropTypes
  • 父组件需提供一个getChildContext函数,以返回一个初始的context对象

如果组件中使用构造函数(constructor),还需要在构造函数中传入第二个参数 context,并在 super 调用父类构造函数是传入 context,否则会造成组件中无法使用 context

...
constructor(props,context){
  super(props,context);
}
...

改变 context 对象

我们不应该也不能直接改变 context 对象中的属性,要想改变 context 对象,只有让其和父组件的 state 或者 props 进行关联,在父组件的 state 或 props 变化时,会自动调用 getChildContext 方法,返回新的 context 对象,而后子组件进行相应的渲染。

import React, { Component } from 'react';
import PropTypes from "prop-types";
import Sub from "./Sub";
import "./App.css";

export default class App extends Component{
    constructor(props) {
        super(props);
        this.state = {
            color:"red"
        };
    }
    // 父组件声明自己支持 context
    static childContextTypes = {
        color:PropTypes.string,
        callback:PropTypes.func,
    }

    // 父组件提供一个函数,用来返回相应的 context 对象
    getChildContext(){
        return{
            color:this.state.color,
            callback:this.callback.bind(this)
        }
    }

    // 在此回调中修改父组件的 state
    callback(color){
        this.setState({
            color,
        })
    }

    render(){
        return(
            <div>
                <Sub></Sub>
            </div>
        );
    }
}

此时,在子组件的 cb 方法中,传入相应的颜色参数,就可以改变 context 对象了,进而影响到子组件。context 同样可以应在无状态组件上,只需将 context 作为第二个参数传入:

import React, { Component } from 'react';
import PropTypes from "prop-types";

const SubSub = (props, context) => {
    const style = { color: context.color }
    const cb = {msg} => {
        return () => {
            context.callback(msg);
        }
    }

    return(
        <div style = {style }>
             SUBSUB
            <button onClick = { cb("我胡汉三又回来了!") }>点击我</button>
        </div>
    )
}

SubSub.contextTypes = {
    color: PropTypes.string,
    callback: PropTypes.func
}

export default SubSub;

非嵌套组件间通信

非嵌套组件,就是没有任何包含关系的组件,包括兄弟组件以及不在同一个父级中的非兄弟组件。对于非嵌套组件,可以采用下面两种方式:

  • 利用二者共同父组件的 context 对象进行通信;
  • 使用自定义事件的方式

如果采用组件间共同的父级来进行中转,会增加子组件和父组件之间的耦合度,如果组件层次较深的话,找到二者公共的父组件不是一件容易的事,当然还是那句话,也不是不可以...

这里我们采用自定义事件的方式来实现非嵌套组件间的通信。
我们需要使用一个 events 包:

npm install events --save

新建一个 ev.js,引入 events 包,并向外提供一个事件对象,供通信时使用:

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

App.js:

import React, { Component } from 'react';

import Foo from "./Foo";
import Boo from "./Boo";

import "./App.css";

export default class App extends Component{
    render(){
        return (
            <div>
                <Foo />
                <Boo />
            </div>
        );
    }
}

Foo.js:

import React, { Component } from 'react';
import emitter from './ev'

import "./App.css";

export default class Foo extends Component{
    constructor(props) {
        super(props);
        this.state = {
            msg: null,
        };
    }

    componentDidMount() {
        //声明一个自定义事件
        //在组件装载完成以后
        this.eventEmitter = emitter.addListener('callme', (msg) => {
            this.setState({
                msg
            })
        });
    }
    //组件销毁前移除事件监听
    componentWillUnmount(){
        emitter.removeListener(this.eventEmitter);
    }
    render(){
        return(
            <div>
                {this.state.msg}
                 我是非嵌套 1 号
            </div>
        )
    }
}

Boo.js:

import React,{ Component } from "react";
import emitter from "./ev"

export default class Boo extends Component{
    render(){
        const cb = (msg) => {
            return () => {
                // 触发自定义事件
                emitter.emit("callMe","Hello")
            }
        }
        return(
            <div>
                我是非嵌套 2 号
                <button onClick = { cb("blue") }>点击我</button>
            </div>
        );
    }
}

自定义事件是典型的发布/订阅模式,通过向事件对象上添加监听器和触发事件来实现组件间通信。

总结

本文总结了 React 中组件的几种通信方式,分别是:

  • 父组件向子组件通信:使用 props
  • 子组件向父组件通信:使用 props 回调
  • 跨级组件间通信:使用 context 对象
  • 非嵌套组件间通信:使用事件订阅

事实上,在组件间进行通信时,这些通信方式都可以使用,区别只在于使用相应的通信方式的复杂程度和个人喜好,选择最合适的那一个。比如,通过事件订阅模式通信不止可以应用在非嵌套组件间,还可以用于跨级组件间,非嵌套组件间通信也可以使用 context 等。关键是选择最合适的方式。

 

 

作者:Charleylla
链接:https://www.jianshu.com/p/fb915d9c99c4
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值