为了使用相同的输入框向单个数组添加值,很可能必须有一个辅助操作(如按按钮),用户需要该操作指示何时存储当前值。
state = {
currentValue: '',
prices: [],
}
onChange = (event) => {
this.setState({ currentValue: event.target.value })
}
addPrice = () => {
this.setState(prevState => ({
prices: [...prevState.prices, this.state.currentValue]
}))
}
...
<input type='text' onChange={this.onChange} value={this.state.currentValue} />
<button onClick={this.addPrice}>Add Price</button>
编辑:您可以在
prices
数组。如果需要键值对,则存储如下对象:
addPrice = () => {
this.setState(prevState => ({
prices: [...prevState.prices, {amount: this.state.currentValue}]
}))
}