React组件通信实现方式详解
目录
1. 父子组件通信方式
✨父子组件之间的通信很常见,其中父组件可以通过props,原型方法向子组件通信,同时子组件也可以用回调函数,事件冒泡向父组件通信
父传子
原型方法
父组件通过React.createRef()创建Ref,保存在实例属性myRef上。父组件
中,渲染子组件时,定义一个Ref属性,值为刚创建的myRef。
父组件调用子组件的myFunc函数,传递一个参数,子组件接收到参数,打印出参数。
this.props
name作为props由父组件传递给子组件,子组件拿到name后,渲染在页面上。参数有父组件传递给子组件
import React, { Component, Fragment } from 'react'; class Son extends Component { myFunc(name) { console.log(name); } render() { return <></>; } } // 父组件 export default class Father extends Component { constructor(props) { super(props); // 创建Ref,并保存在实例属性myRef上 this.myRef = React.createRef(); } componentDidMount() { // 调用子组件的函数,传递一个参数 this.myRef.current.myFunc('Jack'); } render() { return ( <> <Son ref={this.myRef} /> </> ); } }
子传父
- 回调函数
- 事件冒泡
在子组件内部,修改了父组件中的值,从而完成了子组件向父组件通信
import React, { Component } from 'react' class Navbar extends Component{ render(){ return <div red"}}> <button onClick={()=>{ console.log("子通知父, 让父的isSHow 取反。",this.props.event) this.props.event() //调用父组件传来啊的回调函数 }}>click</button> <span>navbar</span> </div> } } class Sidebar extends Component{ render(){ return <div yellow",width:"200px"}}> <ul> <li>11111</li> </ul> </div> } } export default class App extends Component { state = { isShow:false } handleEvent = ()=>{ this.setState({ isShow:!this.state.isShow }) // console.log("父组件定义的event事件") } render() { return ( <div> <Navbar event={this.handleEvent}/> {/* <button onClick={()=>{ this.setState({ isShow:!this.state.isShow }) }}>click</button> */} {this.state.isShow && <Sidebar/>} </div> ) } } /* 父传子 :属性, 子传父: 回调函数 callback */
2. 非父子组件通信方式
- 上一篇 »React中父子组件通信
- 下一篇 »React组件通信浅析