1

在使用 React 的过程中,不可避免的需要组件间进行消息传递(通信),组件间通信大体有下面几种情况:

  1. 父组件向子组件通信
  2. 子组件向父组件通信
  3. 非嵌套组件间通信
  4. 跨级组件之间通信

1.父组件向子组件通信
父组件通过向子组件传递 props,子组件得到 props 后进行相应的处理。
演示代码:
父组件 parent.js:

import React,{ Component } from "react";

export default class App extends Component{

    render(){
        return(
            <div>
                <Sub title = "111111" />
            </div>
        )
    }
}
子组件 child.js:

import React from "react";

class Child extends React.component{

construtor(props){
 super(props)
 this.state = {}
}
render(){
    return(
        <h1>
            { props.title}
        </h1>
    )
}

}

export default Child;

**2.子组件向父组件通信**
利用回调函数,实现子组件向父组件通信:父组件将一个函数作为 props 传递给子组件,子组件调用该回调函数.即可
演示代码:
child.js

import React from "react";

class Child extends React.component{

construtor(props){
 super(props)
 this.state = {}
}
cb = (msg) => {
  this.props.callback(msg);
}
render(){
    return(
         <div>
            <button onClick = { this.cb("通信") }>点击我</button>
        </div>
    )
}

}

export default Child;

app.js

import React from "react";

export default class App extends React.Component{

callback(msg){
    console.log(msg);
}
render(){
    return(
        <div>
            <Sub callback = { this.callback.bind(this) } />
        </div>
    )
}

}

**3.非嵌套组件间通信**
非嵌套组件,就是没有任何包含关系的组件,包括兄弟组件以及不在同一个父级中的非兄弟组件
首先需要引入一个包events

npm install events --save

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

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


app.js

import React, { Component } from 'react';

import childA from "./childA ";
import childB from "./childB";

export default class App extends Component{

render(){
    return(
        <div>
            <childA />
            <childB />
        </div>
    );
}

}

childA

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

export default class ChildA 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 }
            child a
        </div>
    );
}

}

childB:

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

export default class ChildB extends Component{

render(){
    const cb = (msg) => {
        return () => {
            // 触发自定义事件
            emitter.emit("callMe","test")
        }
    }
    return(
        <div>
            childB
            <button onClick = { cb("blue") }>点击</button>
        </div>
    );
}

}


garrett
83 声望0 粉丝

生命不在于你呼吸过多少次,而是那些令你怦然心动到无法呼吸的时刻