我有十几个输入组件。当其中一些没有通过验证时,会得到相应的属性“invalidInputName = true”和类“hasError”。
当用户再次开始输入这些输入时,我需要通过将“invalidInputName”更改为false来删除“hasError”。我想写函数clearValidation()将接受参数名称并将其更改为false。
class ExchangeForm extends React.Component {
constructor(props) {
super(props);
this.state = {
paymentAmountValidation: false,
invalidAccountNum: false,
invalidPhone: false,
invalidCheck: false
}
}
// this function toogles input to normal state.
// I want to pass the name of property which i want to reset
// For example: clearValidation('invalidPhone') must work as
// this.setState({ ...this.state, invalidPhone: false }).
// But best i've done was { property: propery:false } :(
// I have to change this.state only with setState()
clearValidation(property){
this.setState({ ...this.state, property })
}
validation(){
//it toogles state properties to true if found any error
}
}
有可能吗?
答案 0 :(得分:9)
clearValidation(property) {
this.setState({
[property]: false
}
}
有关详细信息,请参阅property accessors docs的括号表示法部分。