React如何父子传值

版权声明:如果觉的本文好的话,点个赞,您的鼓励是我最大的动力。 https://blog.csdn.net/boysky0015/article/details/88362764

众所周知,React父组件给子组件传值通过属性。
父组件

 <div>
   <Input father='父组件传下来的值' />
</div>

子组件Input

<div>
    { this.props.father }
</div>

那么子组件给父组件传值该如何传呢?
一句话可以概括,通过属性把组件的方法传到子组件去执行。

import React,{ Component } from 'react';
import Input from '../../components/Input/Input';

class SonFather extends Component {
    constructor(props) {
        super(props);
    }

    father(value) {
        console.log('father',value);  //这里得到就是子组件的值
    }
    
    render() {
        return (
            <div>
                <Input fatherProps={ this.father.bind(this) }/>
            </div>
        )
    }
}

export default SonFather;

子组件

import React,{ Component } from 'react';
class Input extends Component {
    inputChange(e) {
        let value = e.target.value;
        this.props.fatherProps(value); //父组件中的方法
    }
    render() {
        return (
            <div>
                <input onChange={ this.inputChange.bind(this)} />
            </div>
        )
    }
}
export default Input;

猜你喜欢

转载自blog.csdn.net/boysky0015/article/details/88362764
今日推荐