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

父子组件通信

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

以Header 组件为例
图片描述函数

//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是子组件用父组件的东西,子-父组件通讯,是父组件用子组件的东西,暂时了解的两种方法this

利用回调函数

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

利用ref

父组件经过refs调用子组件的属性设计

跨级组件通讯

在React中当一个属性反复使用而且存在与好几个子组件中的时候,这个时候咱们若是经过props一级一级传递的话能够实现多层级访问,可是这样出现一个问题就是会使代码很是混乱,在React中国年,咱们还可使用 context 来实现跨级父子组件间的通讯;
在react中context称为虫洞code

// 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中,变更时能够自动的同步传递。component

相关文章
相关标签/搜索