如何定义只允许将特定元素类型作为 prop 传递给组件?
假设我有一个组件,它有一个 Prop divider
并且应该以这样的方式输入:<svg>
元素可以传递给此 Prop 。
import { ElementType, ReactElement } from 'react';
type Props = {
divider: ReactElement<'svg'>;
};
export function SVGClipPathSection({ divider: Divider }: Props) {
return (
<div>
<Divider />
Blub
</div>
);
}
这导致
JSX element type 'Divider' does not have any construct or call signatures.ts(2604)
合适的类型是什么?
更新#1
type Props = {
divider: SVGElement;
};
export function SVGClipPathSection({ divider }: Props) {
return <div>{divider}</div>;
}
这导致:
error TS2322: Type 'SVGElement' is not assignable to type 'ReactNode'.
Type 'SVGElement' is missing the following properties from type 'ReactPortal': key, type, props
6 return <div>{divider}</div>;
~~~~~~~~~
node_modules/@types/react/index.d.ts:1375:9
1375 children?: ReactNode | undefined;
~~~~~~~~
The expected type comes from property 'children' which is declared here on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'
最佳答案
我认为你想做的事情是不可能的。
但是,您可以遍历组件数组并过滤所需类型的组件数组,如果存在不需要的类型的子组件,可能会发出警告。
const filtered = divider.filter(e => React.isValidElement(e) && e.type === 'svg');
if (filtered.length !== divider.length) {
console.warn('divider elements must be of type <svg/>');
}
const typed = filtered as ReactElement<React.ComponentProps<'svg'>>[];
编辑:您在 this answer 中很好地解释了为什么您想要的东西可能无法实现。 :
Any react functional component is just a function that has a specific props type and returns
JSX.Element
. This means that if you render the component before you pass it a child, then react has no idea what generated that JSX at all, and just passes it along.And problem is that you render the component with the
<MyComponent>
syntax. So after that point, it's just a generic tree of JSX nodes.
关于reactjs - 只允许特定元素作为由 Typescript 检查的 prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72377929/