reactjs - 只允许特定元素作为由 Typescript 检查的 prop

标签 reactjs typescript

如何定义只允许将特定元素类型作为 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/

相关文章:

reactjs - 在自己的函数中响应导航 onPress

reactjs - React Redux 意外 token ,预期 ","

debugging - 如何调试 webpack bundle 文件错误并在包含数千个的 bundle 中找到确切的错误。 ReactJs 中的行数

javascript - 无法使用类型脚本检查 knockout 中的单选按钮

Angular2 - 从元素中删除禁用的属性

javascript - 检查 `App`的渲染方法

reactjs - 当我将 Flex=1 设置为最顶层 View 时,FlatList 不可见

typescript - 声明窗口 typescript 定义的正确方法

javascript - Angular 2+ 从另一个组件获取 "form.valid"的最佳方法

reactjs - 如何解析 "ethereum.request cannot find name ' 以太坊'"