react开发教程(八)React组件通信
时间:2023-04-05 01:08:48
HTML5
父子组件通信通信方式这是最常见的通信方式。父组件只需要将子组件需要的props传递给子组件,子组件直接使用this.props即可。交流的内容应该更多的是如何合理设置子组件的props。如果要将子组件设计成复用性强的通用组件,就需要对可复用的部分进行抽象。抽象出来的propsFormation有两种,一种是简单的变量,另一种是抽象出来处理某种逻辑功能。以Header组件为例//HeaderBar.jsx子组件importReact,{Component}from'react';classHeaderextendsComponent{constructor(){super();this.handleClick=(e)=>{console.log(this)}}renderLeftComponent(){letleftDOM={};如果(this.props.renderLeftComponent){返回this.props.renderLeftComponent();}if(this.props.showBack){让backFunc=this.props.onBack||这个.goBack;leftDOM=();}返回左DOM;}renderRightComponent(){if(this.props.renderRightComponent){返回this.props.renderRightComponent();}}goBack(){alert("返回上一页")}render(){return({this.renderLeftComponent()}{this.props.title||'滴水'}{this.renderRightComponent()});}}exportdefaultHeader;//父组件App.js的部分代码ximportHeaderBarfrom"./components/Header";letleftIcon=function(){return(leftbutton)}classAppextendsComponent{render(){return(
);}}child-parentcomponentcommunicationparent-childcomponentcommunication方法是使用子组件的props来使用父组件,子父组件通信是使用父组件的子组件。暂时理解的两个方法使用回调函数。父组件通过props传递一个方法给子组件,子组件通过props方法将子组件数据传递给父组件使用ref父组件通过refs调用子组件的属性跨级组件通信在React中,当一个属性被重复使用,存在于几个子组件中,这时候如果我们逐级传递props,就可以实现多级访问,但是有个问题就是会让代码很混乱。在React中,我们还可以使用context来实现父子组件之间的跨级通信;在react中的上下文被称为虫洞//ComponentparentclassparentComponentextendsReact.Component{//添加如下属性staticchildContextTypes={color:React.PropTypes.string}//添加以下方法getChildContext(){return{color:"#f00"}}render(){
}}//ComponentChild1classChild1extendsReact.Component{//添加以下属性staticcontextTypes={color:React.PropTypes.string}render(){
{this.context.color}
}}同级组件同级通信组件之间的通信仍然需要使用父组件作为中介。使用多个父子组件通信,将需要传输的数据放在项目中父组件的state中,变化时自动同步传输。