父组件是调用组件的组件。
现在看来,感觉父组件就是一个壳子,定义好壳子里面会有什么,而子组件是一个具体的实现,说明,会用到什么东西,如果有这些东西,会进行什么操作。总之,父组件是材料,有水和泥,子组件告诉你,怎么制作水泥。
父组件给子组件输入什么,子组件就是什么。不同的父组件调用,或许可以呈现不同的输出,前提是在子组件里面要定义不同的接口,属性方法,供不同的父组件使用。

父子:Parent与Child_1、Child_2、Child_1_1、Child_1_2、Child_2_1
兄弟:Child_1与Child_2、Child_1_1与Child_2、etc
 
一、简单通信
1、父组件向子组件通信(props)
父组件给子组件传递props(属性),实现父组件向子组件的通信。

class Parent extends React.Component {
    state = {
        msg: 'start'
    };

    componentDidMount() {
        setTimeout(() => {
            this.setState({
                msg: 'end'
            });
        }, 1000);
    }

    render() {
        return <Child_1 msg={this.state.msg} />;
    }
}

class Child_1 extends React.Component {
    render() {
        return <p>{this.props.msg}</p>;
    }
}
A、重点
发送方:<Child_1 msg="父组件向子组件通信" />
接收方:<p>{this.props.msg}</p>
B、插播
ES6明确规定,class里面只有静态方法,没有静态属性。自从有了静态属性的提案,可以在class里写实例属性和静态属性。之前都是在constructor里面初始化状态,现在可以直接写状态作为class的实例属性。
2、子组件向父组件通信(回调函数)
父组件给子组件传递props(callback函数),子组件调用该函数,将子组件想要传递的信息,作为参数,传递到父组件的作用域中,实现子组件向父组件的通信。
class Parent extends React.Component {
    state = {
        msg: 'start'
    };

    fMsg(msg) {
        this.setState({
            msg
        });
    }

    render() {
        return (
            <div>
                <p>child msg: {this.state.msg}</p>
                <Child_1 transferMsg={msg => this.fMsg(msg)} />
            </div>
        );
    }
}

class Child_1 extends React.Component {
    componentDidMount() {
        setTimeout(() => {
            this.props.transferMsg('end');
        }, 1000);
    }

    render() {
        return (
            <div>
                <p>child_1 component</p>
            </div>
        );
    }
}
发送方:<Child_1 transferMsg={(msg) => {console.log(msg);}} />
接收方:<a onClick={this.props.transferMsg('子组件向父组件通信')}>子组件发送</a>
3、兄弟组件通信
A、状态提升
兄弟组件不能直接通过props进行消息传递,但是兄弟组件有相同的父元素,因此可以将需要传递的数据挂载在父组件中,由两个兄弟组件共享。
由Child_1向Child_2进行通讯,我们可以先通过Child_1向Parent进行通讯,再由Parent向Child_2进行通讯。
class Parent extends React.Component {
    state = {
        msg: 'start'
    };

    fMsg(msg) {
        this.setState({
            msg
        });
    }

    componentDidUpdate() {
        console.log('Parent update');
    }

    render() {
        return (
            <div>
                <Child_1 transferMsg={msg => this.fMsg(msg)} />
                <Child_2 msg={this.state.msg} />
            </div>
        );
    }
}

class Child_1 extends React.Component {
    componentDidMount() {
        setTimeout(() => {
            this.props.transferMsg('end');
        }, 1000);
    }

    componentDidUpdate() {
        console.log('Child_1 update');
    }

    render() {
        return (
            <div>
                <p>child_1 component</p>
            </div>
        )
    }
}

class Child_2 extends React.Component {
    componentDidUpdate() {
        console.log('Child_2 update');
    }

    render() {
        return (
            <div>
                <p>child_2 component: {this.props.msg}</p>
            </div>
        )
    }
}
这种方式耦合比较严重,父组件承担了本来与自己无关的功能。每次进行消息传递都会触发父组件和子组件的生命周期,如果消息传递比较频繁,会造成很大的浪费。
import eventProxy from '../eventProxy';

class Parent extends React.Component {
    render() {
        return (
            <div>
                <Child_1 />
                <Child_2 />
            </div>
        );
    }
}

class Child_1 extends React.Component {
    componentDidMount() {
        setTimeout(() => {
            // 发布者,发布msg事件
            eventProxy.trigger('msg', 'end');
        }, 1000);
    }
}

class Child_2 extends React.Component {
    state = {
        msg: 'start'
    };

    componentDidMount() {
        // 订阅者,监听msg事件
        eventProxy.on('msg', (msg) => {
            this.setState({
                msg
            });
        });
    }

    render() {
        return (
            <div>
                <p>child_2 component: {this.state.msg}</p>
            </div>
        )
    }
}
4、跨级组件通信
如果父组件与子组件之间不止一个层级,如Parent与Child_1_1这样的关系,该怎么通信呢?
A、层层传递
可通过...运算符(Object 剩余和展开属性),将父组件的信息,以更简洁的方式传递给更深层级的子组件。
// 通过...运算符向Child_1_1传递Parent组件的信息
class Child_1 extends React.Component {
    render() {
        return (
            <div>
                <p>{this.props.msg}</p>
                <Child_1_1 {...this.props} />
            </div>
        )
    }
}

class Child_1_1 extends React.Component {
    render() {
        return <p>{this.props.msg}</p>;
    }
}
B、context对象
context相当于一个全局变量,是一个大容器,我们可以把要通信的内容放在这个容器中,这样一来,不管嵌套有多深,都可以随意取用。
如果是父组件向子组件单向通信,可以使用变量,如果子组件想向父组件通信,同样可以由父组件提供一个回调函数,供子组件调用,回传参数。
上级组件要声明自己支持context,指定组件的childContextTypes属性,并提供一个getChildContext函数来返回初始的context对象;
子组件要声明自己需要使用context,指定组件的contextTypes属性,就可以通过this.context访问这个共同的环境对象。
class Parent extends React.Component {
    getChildContext() {
        return {
            color: 'red',
            cbFun: this.fCallback.bind(this)
        };
    }

    fCallback(msg) {
        console.log(msg);
    }

    render() {
        return <Child_1 />;
    }
}

Parent.childContextTypes = {
    color: PropTypes.string,
    cbFun: PropTypes.func
}

class Child_1 extends React.Component {
    render() {
        return <Child_1_1 />;
    }
}

class Child_1_1 extends React.Component {
    static contextTypes = {
        color: PropTypes.string,
        cbFun: PropTypes.func
    }

    render() {
        const styles = { color: this.context.color };
        const cb = (msg) => {
            return () => {
                this.context.cbFun(msg);
            }
        }
        return (
            <button style={styles} onClick={cb('子组件向父组件传数据。')}>点击</button>
        )
    }
}
我们不应该也不能直接改变context对象中的属性,要想改变context对象,只有让其和父组件的state或者props进行关联,在父组件的state或props变化时,会自动调用getChildContext方法,返回新的context对象,而后子组件进行相应的渲染。

class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            color: "red"
        }
    }

    getChildContext() {
        return {
            color: this.state.color,
            cbFun: this.fCallback.bind(this)
        };
    }

    fCallback(color) {
        this.setState({color});
    }

    render() {
        return <Child_1 />;
    }
}

Parent.childContextTypes = {
    color: PropTypes.string,
    cbFun: PropTypes.func
}
class Child_1 extends React.Component {
    render() {
        return <Child_1_1 />;
    }
}

class Child_1_1 extends React.Component {
    static contextTypes = {
        color: PropTypes.string,
        cbFun: PropTypes.func
    }

    render() {
        const styles = { color: this.context.color };
        const cb = (msg) => {
            return () => {
                this.context.cbFun(msg);
            }
        }
        return (
            <button style={styles} onClick={cb('blue')}>点击</button>
        )
    }
}
二、复杂通信(redux)
三、前往代码
四、底层原理

react组件通信那些事儿的更多相关文章

  1. react第六单元(react组件通信-父子组件通信-子父组件通信-跨级组件的传参方式-context方式的传参)

    第六单元(react组件通信-父子组件通信-子父组件通信-跨级组件的传参方式-context方式的传参) #课程目标 1.梳理react组件之间的关系 2.掌握父子传值的方法 3.掌握子父传值的方法 ...

  2. 21.react 组件通信

    状态属性可以修改 this.setState()中可以写对象,也可以写方法 <script type="text/babel"> class Test extends ...

  3. React/组件通信

    组件通信可以分为以下几种: 父组件向子组件通信 子组件向父组件通信 跨级组件的通信及context 没有嵌套关系的组件通信 父组件向子组件通信   父组件通过props向子组件传递需要的信息.   子 ...

  4. vue组件通信那些事儿

    一.说说通信 通信,简言之,交流信息.交流结束后,把信息放在哪里,这是一个值得思考的问题.vue中保存状态有2种方式,组件内的data属性和组件外的vuex的state属性. 1.用state的场景 ...

  5. React组件通信技巧

    效果图 communication.gif 点击查看Github完整源码 1.父向子通信 直接标签中插入参数即可 //number只是个例子 let _number = this.state.numb ...

  6. React组件通信

    1.父子通信 父 -> 子 props子 -> 父 回调函数,父组件通过props向子组件传递一个函数,子组件调用函数,父组件在回调函数中用setState改变自身状态 2.跨层级通信 1 ...

  7. 使用reflux进行react组件之间的通信

    前言 组件之间为什么要通信?因为有依赖. 那么,作为React组件,怎么通信? React官网说, 进行 父-子 通信,可以直接pass props. 进行 子-父 通信,往父组件传给子组件的函数注入 ...

  8. React之组件通信

    组件通信无外乎,下面这三种父子组件,子父组件,平行组件(也叫兄弟组件)间的数据传输.下面我们来分别说一下: 父子组件: var Demo=React.createClass({ getInitialS ...

  9. 【JAVASCRIPT】React学习- 数据流(组件通信)

    摘要 react 学习包括几个部分: 文本渲染 JSX 语法 组件化思想 数据流 一 组件通信如何实现 父子组件之间不存在继承关系 1.1 父=>子通信 父组件可以通过 this.refs.xx ...

随机推荐

  1. 【kafka】生产者速度测试

    非常有用的参考博客:http://blog.csdn.net/qq_33160722/article/details/52903380 pykafka文档:http://pykafka.readthe ...

  2. Laravel 项目中编写第一个 Vue 组件

    和 CSS 框架一样,Laravel 不强制你使用什么 JavaScript 客户端框架,但是开箱对 Vue.js 提供了良好的支持,如果你更熟悉 React 的话,也可以将默认的脚手架代码替换成 R ...

  3. 网络编程—udp

    一.ip地址 1. 什么是地址 地址就是用来标记地点的 2. ip地址的作用 ip地址:用来在网络中标记一台电脑,比如192.168.1.1:在本地局域网上是唯一的. 3. ip地址的分类 每一个IP ...

  4. WinHex数据恢复笔记(二)

    续写上次笔记: 1.Winhex数据恢复软件的界面上的所有功能已经介绍了一遍,最主要的还是编程恢复的能力. 今天主要看看记事本的编辑恢复及其相关的一些问题,记事本的 编辑值是ASCII值,所以没有文件 ...

  5. bzoj 2761

    神题... 其实这题巨水,用各种诡异的方法都能A,包括STL等等 我之所以写题解,是因为我发现了一个bug:bz和luogu时限有问题! 这题我用了两种做法: ①:直接使用STL-map(不能直接用数 ...

  6. 用HBuilderX 打包 vue 项目 为 App 的步骤

    首先打包你的 vue 项目 生成 dist 文件夹,教程请移步  https://www.cnblogs.com/taohuaya/p/10256670.html 看完上面的教程,请确保 你是 将: ...

  7. 史上最简单的SpringCloud教程 | 第九篇: 服务链路追踪(Spring Cloud Sleuth)

    这篇文章主要讲述服务追踪组件zipkin,Spring Cloud Sleuth集成了zipkin组件. 注意情况: 该案例使用的spring-boot版本1.5.x,没使用2.0.x, 另外本文图3 ...

  8. Mac OS X10.8.3-bash基本命令失效后的修复

    -bash基本命令都失败了. 比如: -bash: ls :command not found   顿时心都凉了. 想要找到.bash_profile文件也不是那么容易的.     step1. 在t ...

  9. SQL Server常见的操作符

    常见的操作符:Sort.Hash Match(聚合).Filter.Compute Scalar等 一:Sort select Shelf from Production.ProductInvento ...

  10. Leetcode刷题第001天

    一.合并两个有序链表 [题目]206. 反转链表 /** * Definition for singly-linked list. * struct ListNode { * int val; * L ...