如何在 onChange 事件上将索引插入数组位置?假设用户可以在任何输入上键入,并且我可以获取数组中的值,该位置必须与输入的索引匹配
onChange = () => {
//so that I get, console.log(this.state.inputGroup)
//expected ['value1', 'value2', 'value3']
}
render() {
return(
<div>
<input onChange={e => this.onChange(1, index)} type="text"/>
<input onChange={e => this.onChange(2, index)} type="text"/>
<input onChange={e => this.onChange(3, index)} type="text"/>
</div>
)
}
最佳答案
您需要将输入中的值传递给 onChange
方法。
所以你通过了e.target.value
。固定索引是第一个参数,这就是指向数组索引的方式。
<input onChange={(e) => { this.onChange(1, e.target.value) }} type="text"/>
以及onChange
方法
onChange = (inputIndex, textValue) => {
//I assume that array of size equal to inputs quantity already is
//declared with ex. empty strings (you can initialize that in
//component constructor)
const inputGroup = this.state.inputGroup
inputGroup[inputIndex] = textValue
this.setState({ inputGroup })
}
顺便说一句。您可能希望以 0 开始输入索引:) 否则数组的 0 元素将永远不会被任何输入使用。
关于javascript - setState react 生成数组结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52421500/