且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在React中将数据从子节点传递给父节点

更新时间:2022-02-07 00:34:43

在父母中定义一个函数并将其发送给child,使用 props 调用子组件中的父函数。类似于:

Define a function in your parent and send it to the child, call the parent function in child component using props. Something like:

class ParentFixturesComponent extends Component {

    // don't forget to bind the function in parent
    constructor() {
        super();
        this.state = {
            numChildren: 0,
        };
        this.someFunctionHere = this.someFunctionHere.bind(this);
    }

    someFunctionHere(param) {
        // do whatever you need
    }

    render() {
        const children = [];
        for (let i = 0; i < this.state.numChildren; i += 1) {
            children.push(<SingleMatchForm key={uuid()}/>)
        }

        return (
            <Fixtures
                addMatch={this.onAddMatch.bind(this)}
                save={this.onSubmit.bind(this)}
                someFunctionHere={this.someFunctionHere}
            >
                {children}
            </Fixtures>
        );
    }
}

export default ParentFixturesComponent;

儿童

class Fixtures extends Component {

    // constructor and other stuff...

    childFunctionHere() {
        this.props.someFunctionHere(params);            
    }

    render() {
        return (
            <div id="fixture-parent" onChange={this.childFunctionHere}>
        );
    }
}

export default Fixtures;