在 React 项目中创建一个 returns 布尔值的函数

Create a function which returns a boolean in React project

我有一些基于特定值是否存在的条件样式。值可以存在也可以是null

background-color: ${myPropValue.myKey !== null ? 'pink' : 'green'};

这很好用。但是,我需要根据此文件中的相同逻辑添加更多条件样式。

我尝试创建一个可以重用的函数:

const hasMyPropValue = ({ myPropValue }: Pick<MyType, 'myPropValue'>) =>
  myPropValue.myKey !== null;

当我想像 background-color: ${hasMyPropValue() ? 'pink' : 'green'}; 那样使用它时,我收到一个 linting 错误:Expected 1 arguments, but got 0.ts(2554)

我只想return是对还是错?

根据我的意见,您使用 class 名称定义了 css 属性。当 ${myPropValue.myKey !== null 然后你添加特定的 class 你想要什么。由此您可以定义多个属性。

I try to create a function which I can reuse: ... I don't want to pass any argument I just want it to return true or false?

对于您所做的两个语句,myPropValue 必须传递参数或在 hasMyPropValue 所在的范围内可用,因为您已按要求键入它。

当您不想传递任何参数时,您可以将参数定义为可选参数,如下所示,也可以为参数提供默认值。

function hasMyPropValue({
  myPropValue = {
    myKey: null
  }
}: {
  myPropValue? : Object
} = {}) {
  return myPropValue.myKey !== null;
}

console.log(hasMyPropValue() ? 'pink': 'green');

我的初始函数几乎正确:

const hasMyPropValue = ({ myPropValue }: Pick<MyType, 'myPropValue'>) =>
  myPropValue.myKey !== null;

但在这里我检查类型是否为 null 类型以及是否为 undefined 类型。这在这种情况下不起作用。

我更改了比较运算符(!= 而不是 !==),然后我的函数就可以工作了。您可以阅读更多相关信息 here

const hasMyPropValue = ({ myPropValue }: Pick<MyType, 'myPropValue'>) =>
 myPropValue.myKey != null;