我当前正在尝试将状态元素(user_number_X
)推入数组(this.state.results.numbers
)中,但是我的输入处理程序功能无法正常工作。
如何重写它,以便将输入值推入数组?
这是我的代码:
export default class InputArea extends React.Component {
constructor(props){
super(props);
this.state = {
draw_number: '',
user_number_1: '',
user_number_2: '',
user_number_3: '',
user_number_4: '',
user_number_5: '',
user_number_6: '',
results : {
numbers: [],
draws: ''
}
}
}
/* handledrawsChange = event => {
this.setState({
event
})
} */
inputHandler = event => {
this.setState({[event.target.name]: event.target.value});
this.state.results.numbers.push(event.target.value)
// this.state.results.numbers.push(event.target.value)//this.setState({number: this.state.results.numbers.push(parseInt(event.target.value))});
}
componentDidMount() {
fetch("http://localhost:8080/simulate", {
method: "POST",
body: this.state.results
});
}
render() {
console.log(this.state);
return (
<InputField>
<InputWrapper>
<Label>1st number</Label>
<Input name="user_number_1" type="number" maxlength="2" value={this.state.user_number_1} onChange={this.inputHandler} required></Input>
<Label>2nd number</Label>
<Input name="user_number_2" type="number" maxlength="2" value={this.state.user_number_2} onChange={this.inputHandler} required></Input>
<Label>3rd number</Label>
<Input name="user_number_3" type="number" maxlength="2" value={this.state.user_number_3} onChange={this.inputHandler} required></Input>
<Label>4th number</Label>
<Input name="user_number_4" type="number" maxlength="2" value={this.state.user_number_4} onChange={this.inputHandler} required></Input>
<Label>5th number</Label>
<Input name="user_number_5" type="number" maxlength="2" value={this.state.user_number_5} onChange={this.inputHandler} required></Input>
<Label>6th number</Label>
<Input name="user_number_6" type="number" maxlength="2" value={this.state.user_number_6} onChange={this.inputHandler} required></Input>
<Label>Number of draws:</Label>
<Input name="draw_number" type="number" value={this.state.draw_number} onChange={this.inputHandler} required></Input>
</InputWrapper>
<Button type="submit" /*onClick={this.drawsHandler}*/>Let's win!</Button>
</InputField>
)
}
}
答案 0 :(得分:1)
您可以使用concat()
进行此操作,并使用对象解构获得更清晰的代码
const {results} = this.state;
const {numbers} = results
this.setState({results:{...results,numbers:numbers.concat([event.target.value])}}