【问题标题】:How to pass this TypeScript React component an optional prop?如何将此 TypeScript React 组件传递给可选道具?
【发布时间】:2021-06-10 20:28:20
【问题描述】:

我对 TS 相当陌生,并试图了解如何将可选道具传递给这个对我来说有点复杂的组件。我以为你可以使用 ?对于您希望成为可选的道具,但我收到以下错误:

绑定模式参数在实现签名中不能是可选的。

我如何将可选的 props 传递给这个组件?

带有可选道具

export const BGVideo = React.memo(function BGVideo({ src, children, bgColor? }: any) {
  return (                                                          ^^^^^^^^
    <BackgroundVideoContainer>...some other stuff...
  )
});

原创

export const BGVideo = React.memo(function BGVideo({ src, children }: any) {
  return (
    <BackgroundVideoContainer>...some other stuff...
  )
});

【问题讨论】:

  • 您可以在类型定义中使用?,但这是冒号的右侧...

标签: reactjs typescript react-typescript


【解决方案1】:

您正在考虑的是声明一个类型的可选属性。例如:

interface Props { bgColor?: string }
const a: Props = { bgColor: '#fff' } // valid
const b: Props = {}                  // valid

但这里代码中的唯一类型是 any,这不是一个好习惯,因为它会禁用所有类型检查。

所以你要做的是为你的道具​​删除 type,其中包括可选属性:

interface Props {
    src: string,
    children: React.ReactNode
    bgColor?: string
}

然后使用那个类型。

export function BGVideo({ src, children, bgColor }: Props) {
  return (
    <>...</>
  )
}

现在在该函数中,bgColor 的类型为 string | undefined。一个string,如果它被传递了一个值,或者undefined,如果它没有被传递一个值。

Working example


最后,React.memo 真的没有必要。您真的不需要以这种方式包装函数组件。 React.memo 更适合您不想重新计算的值。

【讨论】:

    【解决方案2】:

    您尝试添加可选道具的对象是解构的道具对象,而不是道具对象的类型。

    您可以为 props 对象添加类型,如下所示:

    export const BGVideo = React.memo(function BGVideo({ src, children, bgColor }: {src: string, children: React.ReactNode, bgColor?: string}) {
      return (
        <BackgroundVideoContainer>...some other stuff...
      )
    });
    

    或者更好地提取接口或类型中的类型以获得更好的可读性:

    interface BGVideoProps {
          src: string; 
          children: React.ReactNode; 
          bgColor?: string;
        }
    
    export const BGVideo = React.memo(function BGVideo({ src, children, bgColor }: BGVideoProps) {   
      return (
            <BackgroundVideoContainer>...some other stuff...   ) 
    });
    

    这里,bgColor 是一个可选属性

    【讨论】:

      【解决方案3】:

      试试看:

      type Props = {
          src: string;
          bgColor?: string;
          children: React.ReactNode;
      }
      export const BGVideo = React.memo(function BGVideo({ src, children, bgColor }: Props) {
          return (
              <BackgroundVideoContainer>...some other stuff...
          )
      });
      

      【讨论】:

        猜你喜欢
        • 2022-01-10
        • 1970-01-01
        • 1970-01-01
        • 2018-08-01
        • 2020-12-19
        • 1970-01-01
        • 2018-04-25
        • 2015-09-21
        • 1970-01-01
        相关资源
        最近更新 更多