R-5.React组件通信详解

2018-10-24  本文已影响0人  酸菜鱼黄焖鸡

ps:让几个好友看了前几篇文章,提了几个建议,主要就是说文章需要在提炼需要精简
这一章介绍组件通信,组件与组件之间如何传递数据。
概览:

组件通信

1.父子通信

父子组件通信

如图,父子组件之间通信:子组件可通过props接收父组件传递的数据;父组件通过函数回调接收子组件数据。父子对话简单实现如下:

class SimpleFather extends Component{

receptionData = (data) => {
    console.log(`son say:${data}`);// 打印出子组件传回的信息
}

render(){
    return (
        <div>
            <SimpleSon say={'hello son'} whatSaySon={this.receptionData}/>
            {/*通过say属性给子组件传递数据,可传递任何类型,这里是字符串*/}
        </div>
    )
}
}

子组件

class SimpleSon extends Component{

ToResponse = () => {
    const { whatSaySon } = this.props;// 通过props拿到父组件的回调函数
    whatSaySon('hello father');// 执行父组件的回调函数
}

render(){
    // 子组件通过props拿到父组件的值
    const { say } = this.props;
    return (
        <div>
            <p>{say}</p>
            <button onClick={this.ToResponse}>回复</button>
        </div>
    )
}
}

2.跨组件通信

跨组件通信示意图

1).context和函数回调的跨级通信实例

import React,{ Component } from 'react';
const cont = React.createContext('hello everyone');

class SimpleContext1 extends Component{

constructor(props){
    super(props);
    this.state = {
        options:{
            say:'hello',
            callBack:this.receptionData,
        }
    }
}

receptionData = (data) => {
    console.log(`son say:${data}`);// 打印出子组件传回的信息
}

render(){
    const { options } = this.state;
    return (
        <cont.Provider value={options}>
            {/*信息提供者必须被包裹在Provider中,提供的值放在value中*/}
            <div>
                <SimpleContext2/>
            </div>
        </cont.Provider>
    )
}
}

一级子组件

 class SimpleContext2 extends Component{

render(){
    return (
        <div>
            <p>simpleContext2</p>
            <SimpleContext3 />
            {/*组件SimpleContext3没有通过属性传任何值*/}
        </div>
    )
}
}

二级子组件

class SimpleContext3 extends Component{

ToResponse = (value) => {
    const { callBack } = value;// 通过value拿到父组件的回调函数
    callBack('hello father');// 执行父组件的回调函数
}

render(){
    return (
        <cont.Consumer>
            {/*接收信息的组件必须包裹在consumer中,注意下面的书写的格式*/}
            {
                (value) => (
                    <div>
                        <p>{value.say}</p>
                        <button onClick={()=>this.ToResponse(value)}>回复</button>
                    </div>
                )
            }
        </cont.Consumer>
    )
}
}

2).自定义事件通信

自定义事件通信主要用到就是发布订阅模式。这里使用events包来完成。把上面的代码改一哈。

import React,{ Component } from 'react';
import { EventEmitter } from 'events';
const emitter = new EventEmitter();// 负责订阅和发布

class SimpleEvent1 extends Component{

constructor(props){
    super(props);
    this.state = {
        response:'',
    }
}

componentDidMount(){
    // 组件渲染完毕添加事件监听即订阅
    this.response = emitter.on('sayHello',words => {
        this.setState({response: words});
    })
}

componentWillUnmount(){
    emitter.removeListener(this.response);// 组件卸载时清除监听即取消订阅
}

render(){
    const { response } = this.state;
    return (
        <div>
            <p>{response}</p>
            <SimpleEvent2/>
        </div>
    )
}
}

一级子组件

class SimpleEvent2 extends Component{

render(){
    return (
        <div>
            <p>simpleEvent2</p>
            <SimpleEvent3 />
            {/*组件SimpleEvent3没有通过属性传任何值*/}
        </div>
    )
}
}

二级子组件

class SimpleEvent3 extends Component{

ToResponse = () => {
    emitter.emit('sayHello','你好?');// 发布信息,第一个参数一定要与订阅者的一致。
}

render(){
    return (
        <div>
            <p>{}</p>
            <button onClick={this.ToResponse}>回复</button>
        </div>
    )
}
}

3.兄弟组件通信

兄弟共享

就不写例子了。

所有实例都在这里哦:工程源码地址,点击这里
下一章讲解高阶组件
文章所有实例效果图:

工程运行效果
上一篇 下一篇

猜你喜欢

热点阅读