在TypeScript / JSX中更正React.createElement的语法

时间:2017-11-30 20:29:38

标签: reactjs typescript jsx

我无法让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'.

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

2 个答案:

答案 0 :(得分:1)

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

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

interface IColorPickerProps {
    name: string,
    age: number
}

然后

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

如果你输入任何道具,那么你就有点打败了类型检查的目的。

答案 1 :(得分:0)

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