当前位置: 首页 > Web前端 > HTML5

React组件通信的几种方式

时间:2023-04-05 01:05:20 HTML5

最近在做一个react项目,所以简单的了解了一下组件之间的通信方式。概括起来可以分为三类:父子通信-父组件向子组件传递信息子-父通信-子组件向父组件传递信息兄弟通信-兄弟组件相互通信。亲子沟通。这是最简单的通讯方式。在父组件调用子组件的地方添加相应的属性传递,然后在子组件中通过props接收传入的参数信息如下://parentComponentclassParentextendsReact.Component{state={name:this.props.name,age:this.props.age}render(){return(我是父组件框

)}}//子组件constChild=(props)=>{returnI我是一个子组件框名称:{props.name}
年龄:{props.age}
}ReactDOM.render(,document.getElementById('root'))子父通信这种通信比父子通信麻烦,具体步骤如下:父组件在父组件中将回调函数作为参数传递给子组件子组件通过this.props并通过this.props调用父组件提供的回调函数父组件成功接收到子组件传递的消息component下面的数据是一个简单的代码实现://父组件classParentextendsReact.Component{//提供回调函数接收子组件传过来的数据state={name:''}getChildMsg=data=>{console.log('子组件传过来的信息是:'+data)this.setState({name:data})}render(){return(我是父组件box
Name:{this.state.name}
Age:
)}}//子组件类ChildextendsReact.Component{state={name:'yiyi',}handleClick=()=>{this.props.getMsg(this.state.name)}render(){return(我是子组件框
)}}ReactDOM.render(,document.getElementById('root'))兄弟组件之间的通信比上面两种方法稍微复杂一点。具体思路是,状态提升会将共享状态提升到公共父组件,父组件负责管理这个状态。下面的方法是我实现的简单代码:/*将兄弟组件共享的状态提升到父组件。父组件也需要提供更新状态的方法*///父组件类CounterextendsReact.Component{//提供共享状态state={count:0}//提供修改状态的方法handleAdd=()=>{this.setState({count:this.state.count+1})}render(){return(
)}}//子组件1constChild1=(props)=>{return

counter:{props.count}

}//子组件2constChild2=(props)=>{//调用父组件的加一方法returnprops.add()}>Click我加一个}好了,以上就是看完组件通讯后的总结~~欢迎大神指正