在 React 中设置特定组件的状态

Set state on specific component in React

我在一个页面上呈现了许多相同的组件,我的用户可以根据需要添加更多相同的子组件。当他们在子组件的表单元素中选择日期时,我只想更改他们选择的子组件的日期。目前它更改了屏幕上所有子组件的日期,有人能看出我哪里出错了吗?

class ParentFixturesComponent extends Component {

    constructor() {
        super();
        this.state = {
            numChildren: 0,
            startDate: moment(),
            id: uuid()
        };
    }

    changeDate(newDate) {
        this.setState({
            startDate: newDate
        });
    }

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

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

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

}

export default ParentFixturesComponent;

子组件

class SingleMatchForm extends Component {

    handleChange(params) {
        this.props.changeDate(params);
    }

    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.props.startDate}
                            onChange={this.handleChange.bind(this)}/>
                        <div className="section-divider mb40" id="spy1"> </div>
                    </div>
                </div>
            </div>
        );
    }

}

export default SingleMatchForm;

原因是,您正在使用单个 state 变量来保存所有子组件的日期值,如果您更新该单个 state 值,它将影响所有组件。要解决此问题,请使用 array 而不是单个值。

像这样:

this.state = {
    numChildren: 0,
    startDate: [],  //array
    id: uuid()
};

现在每个子组件使用这个array的每个值,并在onChange方法中绑定索引来更新具体值,像这样:

children.push(<SingleMatchForm startDate={this.state.startDate[i] || moment()}
                                           key={this.state.id}
                                           changeDate={this.changeDate.bind(this, i)}
            />)

并在 onChange 方法内部更新特定值而不是所有值:

changeDate(i, newDate) {
    let startDate = this.state.startDate.slice();
    startDate[i] = newDate;
    this.setState({
        startDate
    });
}

I only want to change the date of the child component they selected.

然后子组件应该将 date 作为其状态,或者让父组件将所有子组件的日期保存在一个数组中。