React组件之间传值(学习笔记)

父子组件传值都是通过props, 父传子直接传数据,子传父要传一个函数。然后在子组件中调用这个函数把值传到父组件

父传子:props传值


// 父组件
import React, { Component } from 'react';
import Child from './Child';
class Parent extends Component {
  state = {
    data: '传给子组件的数据'
  }
  render() {
    const { data } = this.state
    return (
      <div className="parent">
        <Child data={ data } />
      </div>
    );
  }
}
// 子组件
import React, { Component } from 'react';
class Child extends Component {
    render() {
        const { data } = this.props
        return (
            <div className='child'>
                <div>父组件传过来的数据:{ data }</div>
            </div>
        );
    }
}

子传父:回调函数


// 父组件
import React, { Component } from 'react';
import Child from './Child';
class Parent extends Component {
    updateData = (data) => {
        console.log('接收来自子组件的数据', data)
    }
  render() {
    return (
      <div className="parent">
        {/*通过props传递一个函数给子组件*/}
        <Child updateData={ this.updateData } />
      </div>
    );
  }
}
// 子组件
import React, { Component } from 'react';
class Child extends Component {
    handleSendData = () => {
        // 子组件通过props调用父组件传过来的函数,并把数据传过去
        this.props.updateData('子组件数据')
    }
    render() {
        return (
            <div className='child'>
                <button onClick={this.handleSendData}>发送数据给父组件</button>
            </div>
        );
    }
}

兄弟组件传值:发布订阅


兄弟组件传值可以借助pubsub-js库。

  1. 安装
npm i pubsub-js
  1. 引入
import PubSub from "pubsub-js";
  1. 使用

在需要发送消息的地方,我们可以使用 publish 方法

import React, { Component } from 'react';
import PubSub from "pubsub-js";
class Child extends Component {
    handleSendDataToBrother = () => {
        PubSub.publish('brotherEvent', '来自兄弟组件的数据123')
    }
    render() {
        return (
            <div className='child'>
                <button onClick={this.handleSendDataToBrother}>发送数据给兄弟组件</button>
            </div>
        );
    }
}
export default Child;

在需要接收消息的地方,我们需要使用 subscribe 方法进行订阅。不需要接收消息时,通过unsubscribe取消订阅

import React, { Component } from 'react';
import PubSub from "pubsub-js";
class Brother extends Component {
    state = {
        data: ''
    }
    componentDidMount() {
        this.subscription = PubSub.subscribe('brotherEvent', (name, data) => {
            console.log('data', data);
            this.setState({
                data
            })
        })
    }
    componentWillUnmount() {
        // 当不再需要接收消息时,记得取消订阅
        PubSub.unsubscribe(this.subscription);
    }
    render() {
        return (
            <div>
                接收来自兄弟组件的数据: {this.state.data}
            </div>
        );
    }
}

export default Brother;
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容