在React中将数据从子节点传递给父节点 [英] Pass data from child to parent in React

查看:90
本文介绍了在React中将数据从子节点传递给父节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在React中有3个组件,其中一个组件作为一个容器传递我的子组件以在表单中呈现。提交表单时,我希望获取父组件中的每个子组件,遍历每个组件,创建我的服务器所期望的对象,然后将对象列表发送回服务器。我正在努力访问我的父组件中的onSubmit函数中的子组件。

I have 3 components in React, one acts as a container which passes down my child components to be rendered in a form. When the form is submitted I want to get each of the child components in my parent component, loop through each one, create an object my server expects then send the list of objects back to the server. I am struggling to access the child components in my onSubmit function in my parent component.

这是我的父组件

ParentFixturesComponent.js

ParentFixturesComponent.js

class ParentFixturesComponent extends Component {

    constructor() {
        super();
        this.state = {
            numChildren: 0,
        };
    }

    onAddMatch() {
        this.setState({
            numChildren: this.state.numChildren + 1
        });
    }

    onSubmit(e) {
        e.preventDefault();
        // loop through the child components
        // create a match object with them
        // var match = {
        //     id: uuid(),
        //     title: uuid(),
        //     start: e.something,
        //     end: e.something,
        // };
        console.log("submit works");
    }

    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)} >
                {children}
            </Fixtures>
        );
    }

}

export default ParentFixturesComponent;

保存我的表单的组件,其中我的父母呈现我的所有子组件

Component which holds my form where my parent renders all my children components

ChildFixturesContainer.js

ChildFixturesContainer.js

class Fixtures extends Component {


    constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(name) {
        this.console.log(this.props);
    }

    render() {
        return (
            <div className="tray tray-center">
                <div className="row">
                    <div className="col-md-8">
                        <div className="panel mb25 mt5">
                            <div className="panel-heading">
                                <span className="panel-title">Fixtures</span>
                            </div>
                            <div className="panel-body p20 pb10">
                                <div id="fixture-parent" onChange={this.handleChange.bind(this)}>
                                    {this.props.children}
                                </div>
                            </div>
                            <div className="section-divider mb40" id="spy1"> </div>
                            <button className="btn btn-primary tm-tag" onClick={this.props.addMatch}>Add Match</button>
                            <button className="btn btn-alert tm-tag" onClick={this.props.save}>Save</button>
                        </div>
                    </div>
                </div>
            </div>
        );
    }

}

export default Fixtures;

最后是我的孩子个人表单组件。

And finally my child individual form component.

SingleMatchComponent.js

SingleMatchComponent.js

class SingleMatchForm extends Component {

    constructor() {
        super();
        this.state = {
            startDate: moment()
        };
    }

    handleChange(date) {
        this.setState({
            startDate: date
        });
    }

    render() {
        return (
            <div className="row">
                <div key={this.props.id} className="form-group">
                    <label className="control-label col-md-2">New Match</label>
                    <div className="col-md-6">
                        <DatePicker
                            selected={this.state.startDate}
                            onChange={this.handleChange.bind(this)}/>
                        <div className="section-divider mb40" id="spy1"> </div>
                    </div>
                </div>
            </div>
        );
    }

}

export default SingleMatchForm;


推荐答案

在父母中定义一个函数并将其发送给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;

这篇关于在React中将数据从子节点传递给父节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆