首页 > 解决方案 > 如何重构箭头函数以使用 if 语句?

问题描述

我有这些箭头功能:

handleTest = () => {
        this.setState({ test: {a: true}})
    }
    handleTest1 = () => {
        this.setState({ test1: {a: false}})
    }

我在一个组件中这样称呼它们:

this.props.handleTest();

this.props.handleTest1();

但我想要这样的东西:

handleTest = (a) => {
    if(a == 'test'){
         this.setState({ a: true })
    }
    else if(a == 'test1'){
        this.setState({ a: false })
    }
} 

并像这样调用该函数,例如:

this.props.handleTest("test");

我怎样才能做到这一点?

非常感谢!

标签: javascriptreactjs

解决方案


如果您的状态逻辑中只有两种可能性,那么您可以使用三元语句。

// Your arrow function which is passing through props
handleTest = (condition = undefined) => {
  this.setState({ a: Boolean(condition) });
}

// Calling
const { handleTest } = this.props;

handleTest('test'); // true
handleTest(); // false

推荐阅读