【问题标题】:Typings for React.createElement are invalidReact.createElement 的输入无效
【发布时间】:2020-12-21 16:27:07
【问题描述】:

如何将 React.createElement 与 TypeScript 一起使用?

import React from "react";


type Props = {
  label: string;
};

const Three: React.FC<Props> = (props: Props) => {
  return <div>{props.label}</div>;
};

/**
 * Three component expects `label` prop
 * But here it is `undefined` - props argument should be second argument
 * Such behaviour leads to error in runtime
 */
const MainButton = (prop: Props) => React.createElement(Three);

export default MainButton

Demo1 Demo2

  "dependencies": {
    "react": "17.0.0",
    "react-dom": "17.0.0",
    "react-scripts": "3.4.3",
    "typescript": "4.1.3"
  },

这是我的解决方法。这里我设置了props 必填参数,因为here 它们是可选的,即使组件具有属性。

const createElement = <T,>(Comp: FC<T>, props: T) => React.createElement(Comp, props);

我错过了什么吗? 我了解 TS 不会抱怨缺少道具,因为它们是可选的。 您如何解决此类问题?

我想在 Github 上创建一个问题,但决定先到这里。

【问题讨论】:

    标签: reactjs typescript react-typescript


    【解决方案1】:

    您需要将道具传递给子元素:

    const MainButton = (prop: Props) => React.createElement(Three, props);
    

    或者:

    const MainButton = (prop: Props) => React.createElement(Three, {label: props.label});
    

    或者更好的是,只需使用Three 作为默认导出。无需创建函数来实例化元素。

    【讨论】:

    • 谢谢,没有那样想))
    猜你喜欢
    • 2017-12-22
    • 2020-04-25
    • 2018-07-22
    • 2019-08-19
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 2017-07-17
    相关资源
    最近更新 更多