typescript 如何将React子元素的类型限制为span元素

2izufjch  于 7个月前  发布在  TypeScript
关注(0)|答案(2)|浏览(108)

我的当前组件看起来如下所示:

interface MyComponentProps {
   children: HTMLSpanElement
}

...

export default function MyComponent({children}: MyComponentProps){
   ...
   return (
      <div>
         {children}
      </div>
   )
}

字符串
我希望我的孩子们只允许一个跨度,没有其他元素。
问题是,我在{children}下面得到一个错误,告诉我Type HTMLSpanElement is not assignable to ReactNode
似乎任何HTMLElement都会发生这种情况,给出错误Type HTMLElement is not assignable to ReactNode
我很好奇,是否有一种方法可以正确处理这种情况,或者其他一些方法可以设置一个示例,在这个示例中,我输入check只传递span元素作为React元素的子节点。

ssm49v7z

ssm49v7z1#

import React from 'react';

interface MyComponentProps extends React.PropsWithChildren<HTMLSpanElement>  {
  hello: 'world' // if needed some extra props
};

export default function MyComponent({children}: MyComponentProps){

  return (
     <div>
        {children}
     </div>
  )
}

字符串
_或使用type而不是interface

type MyComponentProps = React.PropsWithChildren<HTMLSpanElement> & {
  hello: 'world'
};

rn0zuynd

rn0zuynd2#

您可以将React's React.ReactElement类型沿着使用React.ReactElementProps实用程序类型。下面是一个如何限制children属性仅接受span元素的示例:

import React, { ReactElement, ReactElementProps } from 'react';

interface MyComponentProps {
children: ReactElement<ReactElementProps<'span'>>;
}

export default function MyComponent({ children }: MyComponentProps) {
  return (
   <div>
    {children}
   </div>
  );
}

字符串
现在,当你使用MyComponent时,TypeScript会强制只将span元素(或具有span兼容props的组件)作为子元素传递。如果你试图传递任何其他元素或组件,TypeScript将引发类型错误。
就像这样:

import React from 'react';
import MyComponent from './MyComponent';

function App() {
  return (
   <MyComponent>
     <span>Hello, World!</span>
   </MyComponent>
 );
}

相关问题