父子组件通讯
通讯手段
这是最常见的通信方式,父组件只需要将子组件需要的props传给子组件,子组件直接通过this.props来使用。
通讯内容
更多要提的是如何合理的设置子组件的props,要想将子组件设计成一个复用性强的通用组件,需要将能够复用的部分抽象出来,抽象出来的props有两种形成,一种是简单的变量
,另一种是抽象出来处理某种逻辑函数
。
以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是子组件用父组件的东西,子-父组件通信,是父组件用子组件的东西,暂时了解的两种方法
利用回调函数
父组件通过props传递一个方法给子组件,子组件通过props方法将子组件数据传递给父组件
利用ref
跨级组件通信
在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中,变动时可以自动的同步传递。