【问题标题】:Typescript ReactDOM renders children type errorTypescript ReactDOM 呈现子类型错误
【发布时间】:2020-07-17 12:22:56
【问题描述】:

我想通过ReactDOM.render() 渲染多个孩子。我收到以下类型错误:

Argument of type 'ReactNode' is not assignable to parameter of type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)>) | (new (props: any) => Component<any, any, any>)>[]'.
      Type 'string' is not assignable to type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)>) | (new (props: any) => Component<any, any, any>)>[]'.
interface LegacyPageProps {
  children?: React.ReactNode;
}

const LegacyPage: React.FC<LegacyPageProps> = ({ children }) => {
  useEffect(() => {
      const content: HTMLElement = document.querySelector('#react_content');
      if (content) {
        ReactDOM.render(children, content);
      }
  }, [ref, data, children]);

  return ...
}

用于此目的的正确类型是什么?孩子们需要添加到#react_contentid,因为这个应用程序的目标是将 React 集成到遗留应用程序中。新旧内容混合在一起。

FIX: 将子项包装在 React.Fragment 中: ReactDOM.render(&lt;&gt;children&lt;/&gt;, content);

【问题讨论】:

  • 请提供一个儿童示例。
  • 子可以是任何 React 组件。在这种情况下,没有提供孩子。

标签: reactjs typescript


【解决方案1】:

您可以使用 Portal,这是否符合您的需求?

const LegacyPage: React.FC = ({ children }) => {
  return ReactDOM.createPortal(children, document.querySelector('#react_content'));
}

您也不需要定义 children Prop,因为它是 React.FC 的类型。

【讨论】:

    猜你喜欢
    • 2016-08-15
    • 2018-02-25
    • 2022-06-21
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 2020-06-16
    • 2022-01-22
    • 2020-09-15
    相关资源
    最近更新 更多