天天看点

react子组件给父组件传值

子组件给父组件传值:

子组件的代码:

render() {
        return (
            <div>
                {/*当input的值改变时将子组件的值传给父组件,toFatherValue是父组件一个属性,用来接口子组件的值*/}
                <input onChange={(e) => {
                    this.props.toFatherValue( e.target.value);
                }}/>
                {/*点击按钮是给父组件传值*/}
                <button type="button" onClick={this.props.toFatherValue.bind(this, "我是子组件EventComponet的值")}>向父组件传值</button>
            </div>
        )
    }
           

父组件代码

render() {
        var name = "<span style='color: #FF0000;'>张三</span>";
        return (
            <div>
                {/*父组件接收子组件的值*/}
                <EventComponet toFatherValue={this.getChildValue.bind(this)}/>
                <div>从父组件接收过来的值:{this.state.childValue}</div>
            </div>
        )
    }

/**
     * 获取从子组件传递过来的值
     */
    getChildValue(val) {
        console.log("getChildValue", val);
        this.setState({
            childValue:val
        })
    }
           

子组件给父组件传值另一种写法

//子组件代码
render() {
        return (
            <div>
                {/*当input的值改变时将子组件的值传给父组件,toFatherValue是父组件一个属性,用来接口子组件的值*/}
                <input onChange={this.props.toFatherValue}/> 
            </div>
        )
    }
//父组件代码
 render() {
        return (
            <div> {/*父组件接收子组件的值*/}
                <EventComponet toFatherValue={this.getChildValue.bind(this)}/>
                <div>从父组件接收过来的值:{this.state.childValue}</div>
            </div>   )
    }
	/**
     * 获取从子组件传递过来的值
     */
 getChildValue(e) {
        console.log("getChildValue", e.target.value);
        this.setState({
            childValue:e.target.value
        })
    }
           

继续阅读