我正在开发一个 React 项目,我的页面中有一些文本字段。我希望能够单独修改这些输入,同时仍然使用相同的处理程序。
当我尝试输入内容时,收到错误无法读取未定义的属性“相关”
这是我创建的函数:
handleChange(type) {
console.log(type) // outputs "one", "two', "three" when I reload the page
return (event, type) => {
console.log(event) // output the event when I type in the input
console.log(event.target.value) // output the value (the letter I typed)
console.log(type) // output undefined
this.setState(prevState => ({
userInformation : {
...prevState.userInformation,
[type] : {
relevant: this.state.userInformation[type].relevant,
other : event.target.value
}
}
}))
}
}
输入:
<input type="text" value={this.state.userInformation.one.other} onChange={this.handleChange('one')} className="probleme" />
<input type="text" value={this.state.userInformation.two.other} onChange={this.handleChange('two')} className="probleme" />
<input type="text" value={this.state.userInformation.three.other} onChange={this.handleChange('three')} className="probleme" />
国家:
this.state = {
userInformation: {
one: {
relevant: [ ],
other: '',
},
two: {
relevant: [ ],
other: '',
},
three: {
relevant: [ ],
other: '',
}
},
有什么想法吗? 感谢您的宝贵时间!
最佳答案
像这样更新您的代码:
class MyAwesomeComponent {
constructor(props){
this.state = {
one: '',
two: '',
three: ''
}
}
handleChange = (evt)=> {
const {name, value} = evt.target
this.setState({...this.state, [name]: value})
}
render(){
return(
<React.Fragment>
<input name="one" type="text" value={this.state.one} onChange={this.handleChange} className="probleme" />
<input name="two" type="text" value={this.state.two} onChange={this.handleChange} className="probleme" />
<input name="three" type="text" value={this.state.three} onChange={this.handleChange} className="probleme" />
</React.Fragment>
)
}
}
关于javascript - 如何对不同的输入使用相同的处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60116542/