react开发教程(八)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是子组件用父组件的东西,子-父组件通信,是父组件用子组件的东西,暂时了解的两种方法 利用回调函数父组件通过props传递一个方法给子组件,子组件通过props方法将子组件数据传递给父组件 利用ref父组件通过refs调用子组件的属性 跨级组件通信在React中当一个属性反复使用并且存在与好几个子组件中的时候,这个时候我们如果通过props一级一级传递的话可以实现多层级访问,但是这样出现一个问题就是会使代码非常混乱,在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> } } 同级组件通信
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |