react组件间怎么通信 父组件和子组件之间 组件和子组件之间

原创
小哥 3年前 (2022-10-20) 阅读数 29 #Web前端

父组件和子组件之间的通信

父传子

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.name},address:{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组件收到的用户名: {value => { return { ${value.username},年龄是${value.age} } }

) }

兄弟组件之间的通信

通常使用同级组件 props 以父组件作为中间点传递,

任意组件之间的通信

通常使用 redux 作为一种集中式状态管理工具,它处理组件间通信,没有关联或深度嵌套级别。

redux 详细信息可见 redux入门详解

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除