我是React的新手,我试图从2个相同的组件()中获得2个不同的状态
//parent component
updateData = (value) => {
this.setState({ name: value })
};
render() {
return (
<div className="date-picker-container">
<form>
<div className="row">
<CalendarInput id="vacationStart" updateData={this.updateData} placeholder="Начало сезона" />
<CalendarInput id="vacationEnd" updateData={this.updateData} placeholder="Окончание сезона" />
</div>
</form>
</div>
);
}
//And then in child component (<CalendarInput />) I'm calling my updateData function
onClick={() => {this.props.updateData('hello world');}}
答案 0 :(得分:1)
//parent component
updateData = (name, value) => {
this.setState({ [name]: value })
};
//No need of id
render() {
return (
<div className="date-picker-container">
<form>
<div className="row">
<CalendarInput updateData={(value) => {this.updateData('vacationStart', value)}} placeholder="Начало сезона" />
<CalendarInput updateData={(value) => {this.updateData('vacationEnd', value)}} placeholder="Окончание сезона" />
</div>
</form>
</div>
);
}
答案 1 :(得分:0)
您可以通过在将父组件内部的onClick处理程序传递给子组件的同时添加ID和值来做到这一点。
//parent component
updateData = (id, value) => {
id === 'vacationStart' ?
this.setState({ name: value }) :
this.setState({ name: value })
};
render() {
return (
<div className="date-picker-container">
<form>
<div className="row">
<CalendarInput id="vacationStart" updateData={this.updateData('vacationStart', 'Hello World')} placeholder="Начало сезона" />
<CalendarInput id="vacationEnd" updateData={this.updateData('vacationEnd', 'Hello new World')} placeholder="Окончание сезона" />
</div>
</form>
</div>
);
}
//Child component
onClick={this.props.updateData}