setState 反应以生成数组结果



如何在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 元素将永远不会被任何输入使用。

class Test extends React.Component {
constructor(props) {
super(props)
this.state = {
inputGroup: [null, null, null]
}
}
onChange(index, e) {
const inputGroupState = this.state.inputGroup;
inputGroupState[index] = e.target.value;
this.setState({
inputGroup: inputGroupState
},
() => {
console.log(this.state.inputGroup)
}
);
}
render() {
return ( 
<div>
<input onChange = {e => this.onChange(0, e)} type = "text" / >
<input onChange = {e => this.onChange(1, e)} type = "text" / >
<input onChange = {e => this.onChange(2, e)} type = "text" / >
</div>
)
}
}
ReactDOM.render( < Test / > , document.querySelector("#app"))
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

最新更新