React 组件之间传值

本文详细介绍了React中组件之间的通信方式,包括父组件向子组件、子组件向父组件及子组件间的通信。通过props、事件回调、bus事件总线以及context机制进行数据传递,并给出了具体的代码示例。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

一、父组件向子组件传值

父组件向子组件传值 也是通过 props 来传,在子组件中用 this.props.xx 接收父组件传来的值,思路跟 Vue 差不多

父组件代码
import React, { Component } from 'react'
import {HashRouter as Router, Route,Link} from 'react-router-dom'
import Child from './Child'
export default class Parent extends Component {
    constructor(){
        super()
        this.state= {
            name:"张三",
            age:66
        }
    }
    render() {
        return (
            <Router>
                <div>
                    <h3>这是父组件</h3>
                    {/* 这里是把this.state 中的name age 传给子组件 */}  
                    <Child name={this.state.name} age={this.state.age}/> 
                </div>
          
            </Router>
        )
    }
}
子组件代码
import React, { Component } from 'react'

export default class Child extends Component {
   
   
    render() {
        return (
            <div>
                 <h3>这是子组件</h3>
                 {/* 在子组件里通过this.props.xx 接收到父组件传过来的值 */}
                <p>这是父组件传来的值:{this.props.name}</p>
                <p>这是父组件传来的值:{this.props.age}</p>
                
            </div>
        )
    }
}
运行代码得到结果

在这里插入图片描述

二、子组件向父组件传值

子组件 向 父组件 传值 通过 事件传递 + callback 来是实现

子组件代码
import React, { Component } from 'react'

export default class Child extends Component {
    constructor(){
        super()
        this.state = {
            name:'李四',
            age: 18
        }
    }
    //定义一个向 父组件 传值方法
    sendToValueParent = ()=> {
        this.props.callback({
            name: this.state.name,
            age:this.state.age
        })
    }
   
    render() {
        return (
            <div>
                <h3>这是子组件</h3>
                <button onClick={this.sendToValueParent}>传值给父组件</button>
            </div>
        )
    }
}
父组件代码
import React, { Component } from 'react'

import Child from './Child'
export default class Parent extends Component {
    constructor(){
        super();
        this.state = {
            name:'',
            age:''
        }
    }
    //定义一个接收子组件传值的方法
    getChildValue = data => {
        this.setState({  // this.setState({}) 这里赋值有点像 小程序this.setData({})
            name:data.name,
            age:data.age
        })
    }
    
    render() {
        return (
            <div>
                <h3>这是父组件</h3>
                <p>接收子组件传来的值:{this.state.name}</p>
                <p>接收子组件传来的值:{this.state.age}</p>
                <Child callback={this.getChildValue} />
            </div>
        )
    }
}

运行代码:
在这里插入图片描述

然后点击按钮后的结果:

在这里插入图片描述

三、子组件向子组件传值

React 中组件与通过 bus 、 bus.emit(‘xx’,{data})、 bus.on(‘xx’,data=>{}) 来传值;传值的组件用 bus.emit(‘xx’,{data})传值,接收值的组件用 bus.on(‘xx’,data=>{}) 来接收传来的值

bus.js中的代码
import {EventEmitter} from 'events'

const bus = new EventEmitter()

export default bus
brother1 中的代码
import React, { Component } from 'react'
import bus from './bus' /*一定要导入bus */

export default class Brother1 extends Component {

    // dom节点渲染完毕
    componentDidMount(){
        //接收brother2传来的值
        bus.on('sendVal',data=>{
            console.log(data)
        })
    }
    //向brother2传值
    sendValueBrother2 = ()=>{
        bus.emit('sendValue',{
            name:'赵敏',
            age:600
        })
    }
    render() {
        return (
            <div>
                <h3>兄弟1组件</h3>
                <button onClick={this.sendValueBrother2}>传值给兄弟2</button>
            </div>
        )
    }
}
brother2 中的代码
import React, { Component } from 'react'
import bus from './bus' /*一定要导入bus */

export default class Brother2 extends Component {
    
     //向brother1传值
    sendValueBrother1 = ()=>{
        bus.emit('sendVal',{
            name:'周芷若',
            age:600
        })
    }
    // dom节点渲染完毕
    componentDidMount(){
        //接收brother1传来的值
        bus.on('sendValue',data =>{
            console.log(data)
        })
    }

    render() {
        return (
            <div>
                <h3>兄弟2组件</h3> <br/>
                <button onClick={this.sendValueBrother1}>传值给brother1</button>

            </div>
        )
    }
}

运行代码后
在这里插入图片描述
点击按钮:
在这里插入图片描述

context 传给该组件下的所有孙组件

当某个组件在自己的context中保存了某个状态,那个该组件下的所有子孙组件都可以访问到这个状态,不需要中间组件的传递,而这个组件的父组件是没办法访问的

class Index extends Component {
  static childContextTypes = {
    themeColor: PropTypes.string
  }

  constructor () {
    super()
    this.state = { themeColor: 'red' }
  }

  getChildContext () {
    return { themeColor: this.state.themeColor }
  }

  render () {
    return (
      <div>
        <Header />
        <Main />
      </div>
    )
  }
}

通过getChildContext()将属性传递给所有的子孙组件
提供 context 的组件必须提供 childContextTypes 作为 context 的声明和验证。

class Title extends Component {
  static contextTypes = {
    themeColor: PropTypes.string
  }

  render () {
    return (
      <h1 style={{ color: this.context.themeColor }}>标题</h1>
    )
  }
}


子组件要获取 context 里面的内容的话,就必须写 contextTypes 来声明和验证你需要获取的状态的类型,它也是必写的,如果你不写就无法获取 context 里面的状态。
Title 想获取 themeColor,它是一个字符串,我们就在 contextTypes 里面进行声明。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值