Mutual value transfer between react parent component and child component

The advantage of react is its modularity

Therefore, it is often encountered with the value passing of react parent and child components

The following example simply records

 

parent component

 

/**
 * Created by jack on 2017/5/11.
 */
import React from 'react'
import Child_1 from './Child_1'
export  default class Parent  extends React.Component{

    constructor(props) {
        super(props);
        this.state = {
msg:'start'
        };
        this.transferMsg=this.transferMsg.bind(this)
    }



    transferMsg(msg) {
        this.setState({
            msg
        });
    }

    render() {
        return <div>
            <p>child msg: {this.state.msg}</p>
            <Child_1 transferMsg = {a => this.transferMsg(a)}  data={this.state.msg}/>
        </div>;
    }
}
/**
 * Created by jack on 2017/5/11.
 */
import React from 'react'
export  default  class Child_1  extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            m:''
        };
        this.clickhander=this.clickhander.bind(this);
    }


    clickhander(){
        setTimeout(() => {
            this.setState({m:this.props.data})
            if(this.props.data=='start'){
                this.props.transferMsg('end')
            }
            else{
                this.props.transferMsg('start')
            }

        }, 3000);
    }




    render() {
        return <div>
            <p>child_1 component</p>
            <button className="btn btn-info" onClick={ this.clickhander} name="change"/>
        </div>
    }
}

 

 

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326683749&siteId=291194637