我是 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
。
最后,React.memo
真的不是必需的。您真的不需要以这种方式包装功能组件。 React.memo
更适用于您不想重新计算的值。
关于reactjs - 如何将这个 TypeScript React 组件传递给一个可选的 prop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67928065/