父子组件间通信
父传子
1. props
父组件向子组件传递props
,浅谈子组件接收
// 父组件function Parent (){ const [name,setName] = useState('frank') }
函数组件方式的子组件通过参数接收props
并使用
// 子组件 - 函数组件方式 function Child(props) { return ( 接收到的props是{ props.value}); }
class组件方式的子组件通过this.props
调用
// 子组件 - class组件方式class Child extends React.Component{ render(){ return ( 接收到的props是{ this.props.value}) }}
2.ref
父组件通过ref
获取到子组件的实例,可以调用子组件实例中的通信属性或者函数
//子组件class Child extends Component{ state={ name:"admin" } childClickHandle=(city)=>{ this.setState({ address:city }) } render(){ return ( name:{ this.state.address}) }}//父组件class Parent extends Component{ constructor(){ super(); //通过 createRef() 生成ref this.childComp=createRef() } clickHandle=()=>{ //调用子组件的方法,并传递数据 this.childComp.current.childClickHandle("beijing"); } render(){ return ( //给子组件设置ref属性 ) }}ReactDOM.render( ,浅谈 document.getElementById('root'));
子传父
由于react遵循单向数据流
的原则,因此子组件应避免修改通过props
得到的通信值。
正确的浅谈处理方式为父组件将回调函数
作为props
传给子组件,子组件通过调用props
中的通信方法,将数据传回父组件
class Parent1 extends React.Component { state={ ParentMsg:'' } //父组件定义回调函数 getChildMsg = (msg) =>{ console.log('接收到子组件数据:',浅谈msg) this.setState({ ParentMsg:msg }) } render() { return ( 子组件:{ this.state.ParentMsg} //将该函数作为属性的值,传递给子组件 ) }}class Child1 extends React.Component { state={ clidMsg:"老李" } //子组件通过 props 调用回调函数并将子组件的通信数据作为参数传递给回调函数 handleClick = () =>{ this.props.getMsg(this.state.clidMsg) } render() { return ( ) }}export default Parent1;
祖孙组件间通信(跨级通信)
组件A与组件C之间即跨级通信
1. 使用props层层传递
此方法不适用于三层以上的浅谈组件传递
2. context
- 创建一个
context
对象const XxxContext = React.createContext();
- 渲染子组件时,在外层包裹
XxxContext.Provider
,通信通过value
给后代组件传值
子组件
- 后代组件读取数据时,浅谈需要使用
XxxContext.Consumer
声明接收
{ value =>( // value就是通信context中的value数据 要显示的内容 ) }
代码示例:(A-B-C是祖-父-孙的关系)
import React, { Component } from 'react'//创建Context对象const MyContext = React.createContext()export default class A extends Component { state = { username:'tom',age:18} render() { const { username,age} = this.state return ( 我是A组件
我的用户名是:{ username}
) }}class B extends Component { render() { return ( 我是B组件
) }}function C(){ return ( 我是C组件
我从A组件接收到的用户名: { return { `${ value.age}` } }
)}
兄弟组件间通信
兄弟组件间通常利用props
以父组件作为中间点传递,
任意组件间通信
通常使用redux
作为集中状态管理工具,浅谈处理无关联或者嵌套层级深的通信组件间通信
redux
详细内容可见redux入门详解