React 组件通讯的三种方式

父传子,父组件在子组件 Child 标签上绑定一个属性,属性的值为需要传递的参数,子组件通过props获取父组件传递过来的值,如果子组件是类组件,那么,props 为 this.props

import React from 'react'
import ReactDOM from 'react-dom'

// 父组件
class Parent extends React.Component {
    
    
    state = {
    
    
        lastName: "wang"
    }

    render() {
    
    
        return (
            <div className="parent">
                父组件:
                 <Child name={
    
    this.state.lastName}></Child>
            </div>
        )
    }
}

// 子组件
const Child = (props) => {
    
    
    return (
        <div className="child">
            <p>子组件接收到父组件的数据:{
    
    props.name}</p>
        </div>
    )
}

ReactDOM.render(Parent, document.getElementById('root'))

子传父,父组件在子组件Child上绑定一个参数,参数值为一个回调函数,该回调函数需要一个形参(该形参就是子组件传递过来的参数)。子组件事件中使用 prors 调用父组件中定义好的回调函数,参数为需要传递的参数

import React from 'react'
import ReactDOM from 'react-dom'

// 父组件
class Parent extends React.Component {
    
    
    state = {
    
    
        parentMsg: ''
    }
    // 提供回调函数,用来接收数据
    getChildMsg = (data) => {
    
    
        console.log('接收到子组件中传递过来的数据:', data)
        this.setState({
    
    
            parentMsg: data
        })
    }

    render() {
    
    
        return (
            <div className="parent">
                 父组件:{
    
    this.state.parentMsg}
                 <Child getMsg={
    
    this.getChildMsg}></Child>
            </div>
        )
    }
}

// 子组件
class Child extends React.Component {
    
    
    state = {
    
    
        msg: "子组件的数据"
    }
    handleClick = () => {
    
    
        // 子组件调用父组件传递过来的回调函数
        this.props.getMsg(this.state.msg)
    }
    render() {
    
    
        return (
            <div className="child">
                子组件:<button onClick={
    
    this.handleClick}>点我,给父组件传递数据</button>
            </div>
        )
    }
}

ReactDOM.render(Parent, document.getElementById('root'))

兄弟组件之间通讯,将共享状态提升到最近的公共父组件中,由公共父组件管理这个状态(状态提升),也就是把参数先传递给父组件,在由父组件传递给另外一个子组件

import React from 'react'
import ReactDOM from 'react-dom'

// 公共父组件
class Parent extends React.Component {
    
    
    // 提供共享状态
    state = {
    
    
        count: 0
    }

    // 提供修改共享状态的方法
    onIncrease = () => {
    
    
        this.setState({
    
    
            count: this.state.count + 1
        })
    }

    render() {
    
    
        return (
            <div>
                <Child1 count={
    
    this.state.count}/>
                <Child2 onIncrease={
    
    this.onIncrease}/>
            </div>
        )
    }
}

// 子组件1
const Child1 = (props) => {
    
    
    return (
        <h1>计数器:{
    
    props.count}</h1>
    )
}

// 子组件2
const Child2 = (props) => {
    
    
    return (
        <button onClick={
    
    () => props.onIncrease()}>点我+1</button>
    )
}

ReactDOM.Parent (Parent, document.getElementById('root'))

猜你喜欢

转载自blog.csdn.net/weixin_44640323/article/details/121607191