如何在react typescript中输入功能组件prop

s6fujrry  于 2022-12-30  发布在  TypeScript
关注(0)|答案(2)|浏览(218)

我有一个react组件它接受react函数组件作为 prop 。
我的代码:

interface ComponentBProps {
  someComponent?: React.ComponentType;
  msg: string;
}

function ComponentB({someComponent: SomeComponent, msg}: ComponentBProps ) {
  return (
    <div>
      {
        SomeComponent && <SomeComponent>
          <div>
            {msg}
          </div>
        </SomeComponent>
      }
    </div>
  );
}

function ComponentA() {
  return (
    <ComponentB
      someComponent={({children}) => <div>{children}</div>}
      msg="msg"
    />
  );
}

它给了我错误

Type '{ children: Element; }' has no properties in common with type 'IntrinsicAttributes'.
<SomeComponent>
  <div>

以及

Property 'children' does not exist on type '{}'.
<ComponentB
  someComponent={({children}) => <div>{children}</div>}
  msg="msg"
/>

我应该分配给什么类型

someComponent?: React.ComponentType;

React版本:第一个月

gfttwv5a

gfttwv5a1#

如果要强制执行特定的React组件,可以执行以下操作。

const ComponentA: React.FC<{ name: string }> = ({ name }) => <div>hello {name}</div>;

interface PropsB {
  component: typeof ComponentA;
}

const ComponentB: React.FC<PropsB> = ({ component: Component }) => (
  <div>
    <Component name='John' />
  </div>
);

<ComponentB component={ComponentA} />;
50pmv0ei

50pmv0ei2#

我喜欢使用从React导入的FunctionComponent

type Props = {
   component: FunctionComponent<OtherProps>
}

export function SomeComponent({ component: Component }: Props) {
  return <Component />
}

相关问题