react学习(七)______组件通信

在任何框架的使用,都少不了组件之间的相互通信,列如:Vue.js、react。
在react中,主要存在父子组件、子父组件、兄弟组件之间的通信。在项目开发中,组件之间通信必不可少,不然无法完成后续的功能。

父组件===>子组件通信

  • 父子组件的通信主要是依赖props来传递数据的,父组件向子组件绑定一个属性,子组件通过props属性来访问父组件传递过来的属性。
    父组件Parent.js
import React, { Component } from 'react'
import Child from "./Child"

export default class Parent extends Component {
    constructor(){
        super()
        this.state={
            arr:{ name:"胸不平", age:18, sex:"男", brother:"胸不凸" }
        }
    }
    render() {
        return (
            <div>
                <Child {...this.state.arr}></Child>
            </div>
        )
    }
}

子组件Child.js

import React, { Component } from 'react'

export default class Child extends Component {
    render() {
        console.log(this)
        return (
            <div>
                <p>我的名字:{this.props.name}</p>
                <p>我的年龄:{this.props.age}</p>
                <p>我的性别:{this.props.sex}</p>
                <p>我的兄弟:{this.props.brother}</p>
            </div>
        )
    }
}

子组件===>父组件通信

  • 子父组件通过事件来通信的,父组件向子组件传递一个属性,这个属性就是绑定在自身上的方法,子组件通过this.props触发自身的方法函数,就能够实现子父组件之间的通信。
    Parent.js
import React, { Component } from 'react'
import Son from './Son'

export default class Parent extends Component {
    constructor(){
        super()
        this.state={
            sonMsg:'我是傻逼'
        }
    }
    changeSex = (fromSonMsg) => {
        this.setState({
            sonMsg:fromSonMsg
        })
    }
    render() {
        return (
            <div>
                点击子组件的按钮-----改变-----父组件的状态
                sonMsg======>{this.state.sonMsg}
                <Son changeSex={fromSonMsg => this.changeSex.bind(this,fromSonMsg)}></Son>
            </div>
        )
    }
}

Son.js

import React, { Component } from 'react'

export default class Son extends Component {
    render() {
        return (
            <div>
                <button onClick={this.props.changeSex("对的")}>点击改变状态sex</button>
            </div>
        )
    }
}

兄弟组件之间的通信

兄弟组件之间的通信很好理解,例如:Son组件与Child组件之间是兄弟组件关系,他们两是不能够直接通信的,他们唯一有交集的地方就是Parent组件,兄弟组件通信都需要借助父组件来传递的,首先Child组件通过事件与父组件Parent通信,传递Son组件需要的状态,Parent组件接受更改自身的状态在通过props向子组件Son传递Child传来的状态。理论上是可以这样通信的,不过很少人这样搞,这样搞比较麻烦,所以我就不贴代码了。其实组件之间的通信是可以借助redux来解决的,类似Vue中的vuex一样,把状态放入一个公共仓库里面,组件只需要通过一些特定的API方法来连接仓库使用状态就可以了。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。