我有6个使用React-Datepicker的表单输入。我需要使用handleChange()将setState设置6次,但是我不明白如何从每个表单输入中动态获取name属性,因为“ date”在通过函数传递时不包含任何其他数据。我尝试传递“名称”,但是它不起作用。 handleSelect()也是一样
this.state = {
dateOne: new Date(),
dateTwo: new Date(),
dateThree: new Date(),
dateFour: new Date(),
dateFive: new Date(),
dateSix: new Date()
}
handleChange(date) {
this.setState({ ...this.state, ?????: date });
}
handleSelect(date) {
this.setState({ ...this.state, ?????: date });
}
<form>
<DatePicker
name="dateOne"
selected={this.state.dateOne}
onSelect={this.handleSelect}
onChange={this.handleChange}
/>
<DatePicker
name="dateTwo"
selected={this.state.dateTwo}
onSelect={this.handleSelect}
onChange={this.handleChange}
/>
<DatePicker
name="dateThree"
selected={this.state.dateThree}
onSelect={this.handleSelect}
onChange={this.handleChange}
/>
<DatePicker
name="dateFour"
selected={this.state.dateFour}
onSelect={this.handleSelect}
onChange={this.handleChange}
/>
<DatePicker
name="dateFive"
selected={this.state.dateFive}
onSelect={this.handleSelect}
onChange={this.handleChange}
/>
<DatePicker
name="dateSix"
selected={this.state.dateSix}
onSelect={this.handleSelect}
onChange={this.handleChange}
/>
</form>
我也尝试过:https://github.com/Hacker0x01/react-datepicker/issues/242,没有任何运气。
任何帮助都会很棒!
答案 0 :(得分:1)
您可以尝试这样:
<DatePicker
name="dateOne"
selected={this.state.dateOne}
onSelect={this.handleSelect}
onChange={(date)=>this.handleChange(date, 'dateOne')} //pass name as string
/>
handleChange(date, name) {
this.setState({
[name]: data
});
}
因此,您将名称作为字符串传递,因为您无法访问target.name
,然后按名称更新状态,因此您会收到[name]
答案 1 :(得分:-1)
尝试此代码
handleChange(date, flag) {
if(flag===1)
{
this.setState({
dateOne: date
})
}
if(flag===2)
{
this.setState({
dateTwo: date
})
}
if(flag===3)
{
this.setState({
dateThree: date
})
}
if(flag===4)
{
this.setState({
dateFour: date
})
}
if(flag===5)
{
this.setState({
dateFive: date
})
}
if(flag===6)
{
this.setState({
dateSix: date
})
}
}
......
<form>
<DatePicker
name="dateOne"
selected={this.state.dateOne}
onSelect={this.handleSelect}
onChange={(date)=>this.handleChange(date, 1)}
/>
<DatePicker
name="dateTwo"
selected={this.state.dateTwo}
onSelect={this.handleSelect}
onChange={(date)=>this.handleChange(date, 2)}
/>
<DatePicker
name="dateThree"
selected={this.state.dateThree}
onSelect={this.handleSelect}
onChange={(date)=>this.handleChange(date, 3)}
/>
<DatePicker
name="dateFour"
selected={this.state.dateFour}
onSelect={this.handleSelect}
onChange={(date)=>this.handleChange(date, 4)}
/>
<DatePicker
name="dateFive"
selected={this.state.dateFive}
onSelect={this.handleSelect}
onChange={(date)=>this.handleChange(date, 5)}
/>
<DatePicker
name="dateSix"
selected={this.state.dateSix}
onSelect={this.handleSelect}
onChange={(date)=>this.handleChange(date, 6)}
/>
</form>