如何将这个 TypeScript React 组件传递给一个可选的 prop?

How to pass this TypeScript React component an optional prop?

我是 TS 的新手,正在尝试了解如何将可选道具传递给这个对我来说有点复杂的组件。我以为你可以用一个?对于您想要可选的道具,但我收到以下错误:

A binding pattern parameter cannot be optional in an implementation signature.

我如何将可选道具传递给这个组件?

有可选道具

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...
  )
});

试试看:

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...
    )
});

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

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。 A string 如果它被传递了一个值,或者 undefined 如果它没有被传递一个值。

Working example


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

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

您可以按如下方式为道具对象添加类型:

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 是一个可选的属性