【发布时间】:2017-08-21 07:35:57
【问题描述】:
这是我的代码...
class Module extends Component {
constructor() {
super()
this.state = {
inputs: [
{ type: 'text', placeholder: 'placeholder text', name: 'text1', id: 'text1', value: 'aaa' },
{ type: 'text', placeholder: 'another placeholder text', name: 'text2', id: 'text2', value: '' },
{ type: 'text', placeholder: 'third placeholder text', name: 'text3', id: 'text3', value: '' },
]
}
this.handleInputChange = this.handleInputChange.bind(this)
this.saveModule = this.saveModule.bind(this)
}
handleInputChange(event) {
this.setState ({
[event.target.name]: event.target.value
})
}
renderInput = (input) => {
return(
<div key={ input.id }>
<input
type={ input.type }
name={ input.name }
placeholder={ input.placeholder }
onBlur={ this.saveModule }
value={ input.value }
onChange={ this.handleInputChange }
/>
</div>
)
}
render() {
return (
<div>
{ this.state.inputs.map(this.renderInput) }
</div>
)
}
}
export default Module
如何处理以这种方式从状态呈现值的输入变化?! 如果我有 {this.state.input.value} 它工作得非常好,一旦我像这样重构它,setState 似乎不再达到它了。
有什么想法吗? :)
提前非常感谢!
【问题讨论】:
-
首先您必须找到您将处理的对象的索引。所以考虑
event.target.name作为过滤数组的条件。然后使用更改创建一个新数组。并设置状态。这是一个很好的方法stackoverflow.com/a/36010124/7744070
标签: javascript reactjs