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父子组件间的通信

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