ocr*_*ram 2 javascript jsx reactjs
我有一个嵌套对象作为状态,我有一个组件中的表单.我想每次用户在表单中输入内容时更新状态,并避免为每个输入创建许多函数,我正在考虑使用switch创建单个函数.
我尝试使用以下代码但它不起作用:
class App extends Component {
constructor(props) {
super(props)
this.state = {
minutes: null,
interests: {
business: false,
code: false,
design: false
},
errors: []
}
}
updatePreferences = (preferenceName, enteredValue) => {
switch (preferenceName) {
case preferenceName === "minutes":
this.setState({minutes: enteredValue})
return
case preferenceName === "business":
this.setState({interests.business: !this.state.interests.business})
return
case default:
return
}
}
}
Run Code Online (Sandbox Code Playgroud)
当然你可以使用switch,没有错误的AFAIK.
并使用更新嵌套对象setState.查看示例
updatePreferences = (preferenceName, enteredValue) => {
switch (preferenceName) {
case preferenceName === "minutes":
this.setState({minutes: enteredValue});
return
case preferenceName === "business":
this.setState({...this.state, interests: {
...this.state.interests,
business: !this.state.interests.business
}});
return
default:
return
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4134 次 |
| 最近记录: |