React:快速上手(2)——组件通信

React:快速上手(2)——组件通信

向父组件传递数据

  父组件可以通过设置子组件的props属性进行向子组件传值,同时也可以传递一个回调函数,来获取到子组件内部的数据。

效果演示

  子组件是输入框,父组件及时获取到输入框内容然后更新右边标签。

  

父组件传递回调函数

     父组件传递一个方法,即updateSpan,用于更新span内容。

class Father extends React.Component{
    constructor(props){
        super(props)
        this.state = {
            spantxt:null
        }
    }
    /**
     * 更新span中的内容
     * @param {*} txt 
     */
    updateSpan(txt){
        this.setState({
            spantxt:txt
        })
    }
    render(){
        return(
            <div>
                <Son value='1' onChangeHandle={this.updateSpan.bind(this)}/>
                <span>{this.state.spantxt}</span>
            </div>
        )
    }
}

子组件绑定事件

  子组件绑定onChange触发事件txtChange,当内容发生改变txtChange会设置state,同时通过访问prop.onChangeHandle调用了父组件的updateSpan方法,此时参数值即数据就被父组件获取到。

class Son extends React.Component{
    constructor(props){
        super(props)
        this.state = {
            txt:props.value
        }
    }
    render(){
        return(
            <input value={this.state.txt} onChange={this.txtChange.bind(this)}/>
        )
    }
    txtChange(event){
        this.setState(
            {txt:event.target.value}
        )
        this.props.onChangeHandle(event.target.value);
    }
}

  

  

猜你喜欢

转载自www.cnblogs.com/MrSaver/p/10295651.html