我试图从INPUT字段获取用户输入值,并在相应状态下进行更新。但是我在字段中输入的内容并未设置为状态
creatForm(x){
var dx = 'd'+x
let day = 'DAY'+x
return this.state[dx].map((el,i)=>
<div key={i}>
<Form>
<Form.Group inline>
<Form.Field>
<label><h4>{day}</h4></label>
<Input name='startTime' value={el.startTime ||''} onChange={this.handleChange.bind(this,i,dx)}/>
</Form.Field>
<Form.Field>
<Input name='endTime' value={el.endTime ||''} onChange={this.handleChange.bind(this,i,dx)}/>
</Form.Field>
<Form.Field>
<Input name='location' value={el.location ||''} onChange={this.handleChange.bind(this,i,dx)}/>
<Button icon='plus' inverted color='blue' onClick={this.addClick}/>
{this.showMinus(i)}
</Form.Field>
</Form.Group>
</Form>
</div>
)
}
handleChange(i,dx, e) {
const { name, value } = e.target;
let d = [...this.state[dx]];
d[i] = {...d[i], [name]: value};
console.log(d[i])
this.setState({ d });
}
this.state={
d1:[{startTime:'',
endTime:'',
location:''}],
d2:[{startTime:'',
endTime:'',
location:''}],
d3:[{startTime:'',
endTime:'',
location:''}]
}
handleChange 函数是否出错?
答案 0 :(得分:0)
第this.setState({ d });
行将更改不存在状态的属性d
。
您可以在dx
之后添加d
并使用计算属性名称
handleChange(i,dx, e) {
const { name, value } = e.target;
let d = [...this.state[dx]];
d[i] = {...d[i], [name]: value};
console.log(d[i])
this.setState({ [dx]:d });
}