将多个子状态更改传递回父级以进行保存

时间:2016-02-26 05:56:20

标签: meteor reactjs

我有一张桌子,用来显示带有复选标记的客人,表明他们是否参加。我无法想出一种方法将状态从子组件传递给父组件,同时保持它来自哪个子组件的身份。

每一行都是如下所示的组件

guests

将它们渲染到父表容器中,即

guests: [
        {
          pid: new Meteor.Collection.ObjectID(),
          name: "Joe Somebody",
          attending: true,
          hasPlusOne: true,
          plusOneAttending: false
        }

guest对象如下所示。该示例只有一个guest虚拟机,但它可以是一组有效的guest虚拟机,每个guest虚拟机都有一个唯一的PID。

guests

我考虑过将单个<script src='https://connect.humanapi.co/connect.js'></script> <script> var options = { clientUserId: encodeURIComponent('email'), //Unique ID of user on your system (we send this back at the end) clientId: '', publicToken: '', finish: function (err, sessionTokenObject) { /* Called after user finishes connecting their health data */ //POST sessionTokenObject as-is to your server for step 2. console.log(sessionTokenObject); sessionTokenObject.clientSecret = 'Client Secret Key'; $.ajax({ type: 'POST', url: 'https://user.humanapi.co/v1/connect/tokens', method: 'POST', data: sessionTokenObject }) .done(function (data) { console.log(data); // show the response if (data.success) { alert(data.success); } else { alert(data.error); } }) .fail(function (data) { console.log(data); // just in case posting your form failed alert("Posting failed."); }); // Include code here to refresh the page. }, close: function () { /* (optional) Called when a user closes the popup without connecting any data sources */ alert('user clicked on close Button'); }, error: function (err) { /* (optional) Called if an error occurs when loading the popup. */ } } function openHumanApiModel() { HumanConnect.open(options); } </script> 记录的状态添加到父组件,但是当{{1}}有超过2条记录时,它会如何工作?我是否动态添加更多状态项?或者我应该使用refs从子组件中提取数据。但是,我如何唯一地识别每一个并确保我在MongoDb上更新正确的记录?

3 个答案:

答案 0 :(得分:1)

以下是您可以使用的示例代码示例。我所做的是基本的,但也不是100%清洁,我个人可能会略有不同。我还建议你考虑类似Flux的内容。

无论如何,这里是我的伪代码。所以我所做的基本上是以最高形式处于状态,让下面的组件只担心它的道具。这通常是一个很好的模式,您可以根据道具轻松定义行为,并让上面的组件(在状态更改后)为其提供新值。

Form = React.createClass({
    onGuestChange(id, guest){
        //set state with new guests etc
    }

    render() {
        var guestRows = this.state.guests.map(function(guest) {
            return (
                <Guestrow onGuestChange={this.handleGuestChange} data={guest}></Guestrow?
            );
        })
        return() {
            <div>{guestRows}</div>
        }
    }
});

GuestRow = React.createClass({
    handleAttendingChange(id, event){
        var guest = this.props.data
        guest.attending = event.target.checked;
        this.props.onGuestChange(id, guest);
    }

    render() {
        return(
            <div><input type='checkbox' name='attending' checked={this.props.data.attending} onChange={this.handleAttendingChange.bind(this, this.props.data.id)}></input></div>
        );
    }
});

答案 1 :(得分:0)

在您的父级上,创建一个更改状态的函数

// parent component
addMoreGuest(guest) {
   var guests = _.clone(this.state('guests'));
   guests.push(guest);

   this.setState({guests: guests});
}

然后,将addMoreGuest作为回调传递,就像使用onChildChange

一样
<Child callback={this.addMoreGuest} />

在孩子身上,为回调制作一个包装

triggerCallback(guest) {
   this.props['callback'](guest);
}

通过这种方式,您可以将数据从子节点发送到父节点,然后更新父节点的状态。在here

中详细了解相关信息

答案 2 :(得分:0)

万一其他人像我一样最终出现在这里,只需看看这篇中等职位。 Passing Data Between React Components

请务必同时观看此视频React JS Tutorial 10: Passing data from child to parent components

重要的代码在下面的代码中说明

App.js

class App extends Component {

    constructor(props) {
        super(props);
        this.state = {someStateVariable: ''};
        this.callbackFromParentToChild = this.callbackFromParentToChild.bind(this) // IMPORTANT
    }

    // get some value from the child component
    // this callback belongs to the child's context so we have to bind it to
    // this parent's context using this line in the constructor 
    // this.callbackFromParentToChild = this.callbackFromParentToChild.bind(this)

    callbackFromParentToChild(value_from_child_to_parent) {
        this.setState({someStateVariable: value_from_child_to_parent});     
    }

    renderChildComponent() {
       return country_denominations.map((denomination) => (
            <ChildComponent callback_from_parent_to_child={this.callbackFromParentToChild}/>
        ));
    }
}

Denominator.jsx

export default class ChildComponent extends Component {
    computeValueToBePassedToParent() {
        value_from_child_to_parent = '' // perform some computation
        this.props.callback_from_parent_to_child(value_from_child_to_parent); // pass the total back to the parent's callback
    }
}