javascript - 如何重构箭头函数以使用 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");
我怎样才能做到这一点?
非常感谢!
解决方案
如果您的状态逻辑中只有两种可能性,那么您可以使用三元语句。
// 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
推荐阅读
- javascript - 在NodeList中查找html div的位置
- python - 追加二维数组的最佳方法
- javascript - 清除过滤器功能不起作用Vue
- linux - 如何删除 Github 存储库
- angular - 提交后以角度重定向反应形式
- php - 错误:尝试使用 srmklive / laravel-paypal v.3 访问 null 类型值的数组偏移量
- flutter - Wheel ListView 小部件内的颤振按钮
- git - 如何在终端中重命名 git commit
- linux - 运行较新版本的 cURL 时的 SSL_ERROR_SYSCALL(错误 35)
- javascript - 将一个 div 居中并将右侧菜单附加到该 div