Reactjs 如何将此TypeScript React组件传递给可选道具?
我对TS还比较陌生,并且试图了解如何将可选道具传递给这个对我来说有点复杂的组件。我想你可以用一个?对于您希望可选的道具,但我得到以下错误: 绑定模式参数在实现签名中不能是可选的 如何将可选道具传递到此组件 可选道具Reactjs 如何将此TypeScript React组件传递给可选道具?,reactjs,typescript,react-typescript,Reactjs,Typescript,React Typescript,我对TS还比较陌生,并且试图了解如何将可选道具传递给这个对我来说有点复杂的组件。我想你可以用一个?对于您希望可选的道具,但我得到以下错误: 绑定模式参数在实现签名中不能是可选的 如何将可选道具传递到此组件 可选道具 export const BGVideo = React.memo(function BGVideo({ src, children, bgColor? }: any) { return (
export const BGVideo = React.memo(function BGVideo({ src, children, bgColor? }: any) {
return ( ^^^^^^^^
<BackgroundVideoContainer>...some other stuff...
)
});
export const BGVideo=React.memo(函数BGVideo({src,children,bgColor?}:any){
报税表(^^^^^^^^
…其他一些东西。。。
)
});
原创
export const BGVideo = React.memo(function BGVideo({ src, children }: any) {
return (
<BackgroundVideoContainer>...some other stuff...
)
});
export const BGVideo=React.memo(函数BGVideo({src,children}:any){
返回(
…其他一些东西。。。
)
});
试试看:
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...
)
});
类型道具={
src:字符串;
bgColor?:字符串;
子节点:React.ReactNode;
}
export const BGVideo=React.memo(函数BGVideo({src,children,bgColor}:Props){
返回(
…其他一些东西。。。
)
});
您考虑的是声明类型的可选属性。例如:
interface Props { bgColor?: string }
const a: Props = { bgColor: '#fff' } // valid
const b: Props = {} // valid
但是这里代码中唯一的类型是any
,这不是一个好的做法,因为它禁用了所有类型检查
因此,您要做的是删除道具的类型,其中包括可选属性:
interface Props {
src: string,
children: React.ReactNode
bgColor?: string
}
然后用那种类型
export function BGVideo({ src, children, bgColor }: Props) {
return (
<>...</>
)
}
导出函数BGVideo({src,children,bgColor}:Props){
返回(
...
)
}
现在在该函数中,bgColor
的类型为string | undefined
。如果传递了值,则为字符串
;如果未传递值,则为未定义
最后,
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...
)
});
export const BGVideo=React.memo(函数BGVideo({src,children,bgColor}:{src:string,children:React.ReactNode,bgColor?:string}){
返回(
…其他一些东西。。。
)
});
或者最好在接口或类型中提取类型,以提高可读性:
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... )
});
接口BGVideoProps{
src:字符串;
子节点:React.ReactNode;
bgColor?:字符串;
}
export const BGVideo=React.memo(函数BGVideo({src,children,bgColor}:BGVideoProps){
返回(
…其他一些东西…)
});
在这里,bgColor是一个可选属性您可以在类型定义中使用
?
,但那是冒号的右侧。。。