我正在尝试实现复合设计模式。为此,我必须将一个react组件作为属性传递给另一个react组件。
代码如下:
function FlyOut(props) {
return (
<div>
{props.children}
</div>
);
}
function Toggle() {
return (
<div>
<Icon />
</div>
);
}
FlyOut.Toggle = Toggle;
由于我使用的是typescript,所以我必须为这些组件指定类型。
不包含此语句:FlyOut.Toggle = Toggle;
。我指定的打字脚本类型如下:
type FlyoutProp={
children?: ReactNode | undefined;
}
function FlyOut=React.FC<FlyoutProp>(props)=> {
return (
<div>
{props.children}
</div>
);
}
function Toggle:React.FC<void> =()=> {
return (
<div>
<Icon />
</div>
);
}
现在我添加了这个语句FlyOut.Toggle = Toggle;
我试过了:
type FlyoutProps = {
children?: ReactNode | undefined;
};
type ExtendedReactFC = React.FC<FlyoutProps> & {
Toggle?: ReactNode | undefined;
};
function FlyOut=ExtendedReactFC<FlyoutProp>(props)=> {
return (
<div>
{props.children}
</div>
);
}
function Toggle:React.FC<void> =()=> {
return (
<div>
<Icon />
</div>
);
}
FlyOut.Toggle = Toggle;
但是这不起作用。谁能指点我一下?
您需要将ExtendedReactFC<FlyoutProp>
更改为ExtendedReactFC
,因为ExtendedReactFC
不接受泛型
type FlyoutProps = {
children?: ReactNode | undefined;
};
type ExtendedReactFC = React.FC<FlyoutProps> & {
Toggle?: ReactNode | undefined;
};
function FlyOut=ExtendedReactFC(props)=> {
return (
<div>
{props.children}
</div>
);
}
如果你想让它接受泛型类型的道具,你可以把它改成
type FlyoutProps = {
children?: ReactNode | undefined;
};
type ExtendedReactFC<T extends Record<string,any>> = React.FC<T> & {
Toggle?: ReactNode | undefined;
};
function FlyOut=ExtendedReactFC<FlyoutProps>(props)=> {
return (
<div>
{props.children}
</div>
);
}