react 父组件与子组件之间的相互传值

react的优点就在于模块化

所以经常与遇到react 父与子组件的传值

下面这个例子简单的来记录一下

父组件

/**
 * 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>
    }
}

猜你喜欢

转载自guozhijie87.iteye.com/blog/2373912