react开发教程(八)React组件通信

发布时间:2019-06-15 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了react开发教程(八)React组件通信脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

父子组件通讯

通讯手段
这是最常见的通信方式,父组件只需要将子组件需要的PRops传给子组件,子组件直接通过this.props来使用。
通讯内容
更多要提的是如何合理的设置子组件的props,要想将子组件设计成一个复用性强的通用组件,需要将能够复用的部分抽象出来,抽象出来的props有两种形成,一种是简单变量,另一种是抽象出来处理某种逻辑函数

以Header 组件为例

react开发教程(八)React组件通信

//HeaderBar.jsx  子组件

import React, { Component } from 'react';

class Header extends Component {
    constructor() {
        suPEr();
        this.handleClick = (e) => {
            console.log(this)
        }
    }

    renderLeftComponent() {

        let leftDOM = {};
        if (this.props.renderLeftComponent) {
            return this.props.renderLeftComponent();
        }

        if (this.props.showBack) {
            let backFunc = this.props.onBack || this.goBack;
            leftDOM = (<a onClick={backFunc.bind(this)}><i classname="icon left-icon icon-left-arrow"></i></a>);
        }
        return leftDOM;
    }
    

    renderRightComponent() {
        if (this.props.renderRightComponent) {
            return this.props.renderRightComponent();
        }
    }

    goBack() {
        alert("返回上一页")
    }

    render() {
        return (
            <header className="header-bar">
                {this.renderLeftComponent()}
                <span>{this.props.title || '滴滴'}</span>
                {this.renderRightComponent()}
            </header>
        );
    }
}

export default Header;

//父亲组件部分代码App.jsx
import HeaderBar from "./components/Header";

let leftIcon = function () {
  return (
    <a><i className="icon left-icon icon-left-haha"></i>左边按钮</a>
  )
}
class App extends Component {

  render() {
    return (
      <div className="App">
        <HeaderBar title="滴滴打车"  renderLeftComponent={leftIcon} />
      </div>
    );
  }
}

子父组件通讯

父-子组件通信的手段是通过子组件的props是子组件用父组件的东西,子-父组件通信,是父组件用子组件的东西,暂时了解的两种方法

利用回调函数

父组件通过props传递一个方法给子组件,子组件通过props方法将子组件数据传递给父组件

利用ref

父组件通过refs调用子组件的属性

跨级组件通信

React中当一个属性反复使用并且存在与好几个子组件中的时候,这个时候我们如果通过props一级一级传递的话可以实现多层级访问,但是这样出现一个问题就是会使代码非常混乱,在React中国年,我们还可以使用 context 来实现跨级父子组件间的通信;
在react中context称为虫洞

// Component 父级
class parentComponent extends React.Component {
    
    // add the following property
    static childContextTypes = {
        color: React.PropTypes.string
    }
    
    // 添加下面方法
    getChildContext() {
        return {
            color: "#f00"
        }
    }
    
    render() {
        <div>
            <Child1 />
        </div>
    }
}


// Component Child1
class Child1 extends React.Component {
    // 添加下面属性
    static contextTypes = {
        color: React.PropTypes.string
    }
    
    render() {
        <div>{this.context.color}</div>
    }
}

同级组件通信

同级组件之间的通信还是需要通过父组件作为中介,利用多次父-子组件通信,项目中将需要传递的数据放在了父组件的state中,变动时可以自动的同步传递。

脚本宝典总结

以上是脚本宝典为你收集整理的react开发教程(八)React组件通信全部内容,希望文章能够帮你解决react开发教程(八)React组件通信所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。