简体   繁体   English

复选框保持React JS中组件之间的状态

[英]Checkbox keeps state across components in React JS

I'm new in React JS, but I read about <input> that you have to save actual state in onChange like described here: React DOC - Forms 我是React JS的新手,但我读到有关<input> ,您必须将实际状态保存在onChange如此处所述: React DOC-Forms

I have a list with a checkbox and I applied same behavior here in CampaignsRow 我有一个带有复选框的列表,我在CampaignsRow在此处应用了相同的行为

var campaignsData = [{Name: "First"}, {Name: "Second"}, {Name: "Third"}];

var CampaignsRow = React.createClass({
    getInitialState: function() {
        return {checked: false};
    },
    checkedChange: function (e) {
        this.setState({checked: e.target.checked});
    },
    render: function() {
        console.log(this.props.data.Name, this.state.checked);
        return (
            <div className="row">
                <div className="cell checkbox">
                    <input type="checkbox" checked={this.state.checked} onChange={this.checkedChange}/>
                </div>
                <div className="cell campaignName">{this.props.data.Name}</div>
            </div>
        );
    }
});
var CampaignsTable = React.createClass({
    render: function() {
        var rows = this.props.campaigns.map(function(campaign) {
        return (
            <CampaignsRow data={campaign}/>
        );
    });

    return <div className="table">
        <div className="row header">
            <div className="cell checkbox"><input type="checkbox"/></div>
            <div className="cell campaignName">Name</div>
        </div>
        {rows}
    </div>
  }
});

ReactDOM.render(<CampaignsTable campaigns={campaignsData} /> ,document.getElementById('reactContainer'));

My problem is, if I check the checkbox at the campaign with name First and then I remove first item by campaignsData.shift() (to simulate downloading new data from Server) and then render again, checkbox at Second campaign is checked. 我的问题是,如果我选中名称为First的活动中的复选框,然后再通过campaignsData.shift()删除第一项(以模拟从Server下载新数据),然后再次进行渲染,则会选中Second campaign中的复选框。

What is the purpose of this.state when it is not attached to the instance. 未连接到实例时this.state的目的是什么。 Render works fine, because in the console is printed Second true , so this.state.checked was moved from First to Second campaign. 渲染工作正常,因为在控制台中打印Second true ,所以this.state.checked已从First运动移至Second运动。

You should add unique key property to multiple components, so that React can keep track of identities: 您应该向多个组件添加唯一的key属性,以便React可以跟踪身份:

var rows = this.props.campaigns.map(function(campaign) {
    return (
        <CampaignsRow key={campaign.name} data={campaign}/>
    );
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM