如何通过将参数传递给setState()[duplicate]来改变状态

问题描述 投票:0回答:1

这个问题在这里已有答案:

我有十几个输入组件。当其中一些没有通过验证时,它会得到相应的属性“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
    }
}

可能吗?

javascript reactjs
1个回答
7
投票
clearValidation(property) {
    this.setState({
        [property]: false
    }
}

有关更多信息,请参阅property accessors docs的括号表示法部分。

© www.soinside.com 2019 - 2024. All rights reserved.