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

标签 reactjs typescript react-typescript

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

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

我如何将可选 Prop 传递给该组件?

带有可选 Prop

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

最佳答案

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

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

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

所以您要做的是为您的 Prop 删除 类型,其中包括可选属性:

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

然后使用那个类型。

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

现在在该函数中,bgColor 的类型为 string |未定义。如果传递了一个值,则为 string,如果未传递值,则为 undefined

Working example


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

关于reactjs - 如何将这个 TypeScript React 组件传递给一个可选的 prop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67928065/

相关文章:

typescript - typescript 中的 bool 列表是否有 "all"或 "any"运算符

typescript - 命名泛型函数的返回类型

javascript - 从 JSON 对象生成 Material 时间线

javascript - req.body 从 React 客户端到 Express 服务器未定义

javascript - 不知道我做错了什么 - 获取不是函数错误

javascript - 没有上传图片 "SRC"即使检查也未定义?

typescript - TypeScript 有像 Kotlin 这样的扩展吗?

javascript - 当子节点可以是 React 节点或函数时如何使用 React.FC<props> 类型

typescript - 无法使用 JSX,除非我在执行yarn start 时提供了 '--jsx' 标志

javascript - MUI 选择 |更改所选值在输入中的显示方式