我正在生成多个输入,并希望将它们的值绑定(bind)到存储在 state
中的数组。我正在使用数组,因为输入的数量不同,我无法静态创建它们。
我正在分配它们的值(value)并且它按预期工作:
this.setState({
wordInputs: this.state.userTitle.map((word) => {
let input = <input type="text" key={i} value={this.state.userTitle[i]} onChange={this.checkWordInput}/>
i++
return input
})
})
现在我想用 checkWordInput()
处理用户输入,我的问题来了:如何访问输入的 key
属性集以更新 >this.state.userTitle
数组?还是有其他方法可以做到这一点?
最佳答案
我认为你不需要在状态中存储inputs
,你可以将inputs
移动到render
,像这样
class App extends React.Component {
constructor() {
super();
this.state = {
userTitle: [
'title - 1',
'title - 2',
'title - 3',
'title - 4'
]
};
}
checkWordInput(index, e) {
this.setState({
userTitle: this.state.userTitle.map((title, i) => (
i === index ? e.target.value : title
))
})
}
render() {
const inputs = this.state.userTitle.map((title, index) => (
<input
type="text"
key={index}
value={title}
onChange={ (e) => this.checkWordInput(index, e) }
/>
));
return (
<form>
{ inputs }
{ this.state.userTitle.map((title, i) => <p key={i}> { title }</p>) }
</form>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
<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>
关于javascript - 特定数组项的 setState(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41432587/