React父子组件间的通信

作者: 西瓜吐籽不吐皮儿 | 来源:发表于2019-06-27 17:48 被阅读27次

React数据流动是单向的,父组件向子组件的通信也是最常见的方式。父组件通过props向子组件传递需要的信息。子组件向父组件传递信息可以通过回调函数来改变父组件的信息。
父组件

import React, {Component} from 'react';
import Child from '../Child/Child'

class Father extends Component {
    constructor(props) {
        super(props)

        this.callback = this.callback.bind(this)

        this.state = {
            msg: '我是从父组件传到子组件的爸爸',
            info: '我是父组件'
        }
    }

    callback(info) {
        this.setState({info})
    }

    render() {
        return (
            <div>
                <p>{this.state.info}</p>
                <Child callback={this.callback} msg={this.state.msg}/>
            </div>
        )
    }
    
}
export default Father

子组件

import React, {Component} from 'react';

class Child extends Component {
    constructor(props) {
        super(props)

        this.change = this.change.bind(this)

        this.state = {
            msg: '我是从子组件传到父组件的儿子'
        }
    }

    change() {
        this.props.callback(this.state.msg)
    }

    render() {
        return (
            <div>
                <div>{this.props.msg}</div>
                <button onClick={this.change}>按钮</button>
            </div>
        )
    }
    
}
export default Child

上述例子,我将父组件的msg变为子组件的属性传给子组件,子组件通过this.props.msg来接收父组件传过来的信息。当我们按下子组件的按钮,子组件通过父组件传来的回调函数callback来改变父组件中info的值。
结果展示:

点击前 微信图片_20190627174417.png
点击后
微信图片_20190627174447.png

相关文章

  • React父子组件间通信的实现方式

    React学习笔记之父子组件间通信的实现:今天弄清楚了父子组件间通信是怎么实现的。父组件向子组件通信是通过向子组件...

  • 「React Native」Event Bus,消息总线

    (一)父子间组件通信:   一般使用props,回调函数进行通信。(二)跨组件之间通信:  (1)React Na...

  • react-父子组件间通信

    React-父子组件间通信 父组件传 值 给子组件, 传 方法 给子组件 子组件接收 值 ,触发父组件的 方法

  • React父子组件间的通信

    React数据流动是单向的,父组件向子组件的通信也是最常见的方式。父组件通过props向子组件传递需要的信息。子组...

  • 7.3.3Vue非父子间的组件通信

    非父子间的组件通信 父子链 子组件索引

  • vue组件间通信的一些实用方法(VUE2.x)

    vue组件间通信的一些实用方法(VUE2.x) 一、父子组件间通信 常用的父子组件通信方法,一般涉及props和$...

  • vue中的组件间通信

    父子组件相互通信 非父子组件间通信 关于vuex请查阅: https://www.jianshu.com/writ...

  • Vue基础-03 组件间的通信

    1. 组件间的通信 父子间的通信 通过props 父组件: 1.在父组件引入子组件在components:{ } ...

  • React组件间通信

    不借助redux等状态管理工具的React组件间的通信解决方法 组件通信分类 React组件间通信分为2大类,3种...

  • react 组件通信

    概述 react中的组件通信问题,根据层级关系总共有四种类型的组件通信:父子组件、爷孙组件、兄弟组件和任意组件。前...

网友评论

    本文标题:React父子组件间的通信

    本文链接:https://www.haomeiwen.com/subject/cqprcctx.html