【问题标题】:Correct syntax for React.createElement in TypeScript/JSXTypeScript/JSX 中 React.createElement 的正确语法
【发布时间】:2018-05-14 21:22:04
【问题描述】:

我无法让 React.createElement 在 TypeScript 中编译。

interface IColorPickerProps {

}

interface IColorPickerState {

}

class ColorPicker extends React.Component<IColorPickerProps, IColorPickerState> { 
    constructor(props: IColorPickerProps) {
        super(props);
    }
}

组件创建:

let props: any = {}
React.createElement(ColorPicker, props)

我得到这个编译错误:

Argument of type 'typeof ColorPicker' is not assignable to parameter of type 'string | ComponentClass<IColorPickerProps> | StatelessComponent<IColorPickerProps>'.
  Type 'typeof ColorPicker' is not assignable to type 'StatelessComponent<IColorPickerProps>'.
    Type 'typeof ColorPicker' provides no match for the signature '(props: IColorPickerProps & { children?: ReactNode; }, context?: any): ReactElement<any> | null'.

如果我删除构造函数,错误就会消失。我不能使用语法,因为道具需要动态传递。有什么想法吗?

【问题讨论】:

  • 为什么React.createElement(ColorPicker, props) 而你只能&lt;ColorPicker/&gt;
  • 因为 props 作为参数动态传递给创建 ColorPicker 的类。 &lt;ColorPicker myProp={props["name"]}/&gt; 会丢失编译时间检查,而 React.createElement(ColorPicker, props) 不会。

标签: reactjs typescript jsx


【解决方案1】:

我已经通过升级到最新版本的 React 和最新版本的类型定义解决了这个问题,这可能是我使用的类型定义的问题。谢谢大家的帮助

【讨论】:

    【解决方案2】:

    当我运行 filename.tsx,然后运行 ​​node filename.js 时,您的代码对我来说编译得很好。你还有其他代码吗?

    在类中键入道具的全部意义在于让您知道将传递给您的 ColorPicker 类的内容。在我看来,最好的办法是修复您的 IColorPickerProps 接口以包含将像这样传递的道具。

    interface IColorPickerProps {
        name: string,
        age: number
    }
    

    然后

    let myprops: IColorPickerProps = {
        name: ...
        age: ...
    }
    

    如果您将 props 键入为 any,那么您有点违背了类型检查的目的。

    【讨论】:

    • 你是对的,它确实可以编译。我正在使用 VS Code 并且实时 TypeScript 检查确实给了我错误,但它编译得很好。知道为什么吗?至于类型检查,这是一个特殊的工厂类,不知道接收到什么props,必须动态传递props。
    • 我对您收到的道具的意思有点困惑。是不是每次发送的道具数量不同,还是道具类型不同?
    猜你喜欢
    • 1970-01-01
    • 2021-12-16
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    • 1970-01-01
    • 2016-02-01
    相关资源
    最近更新 更多