在TypeScript / JSX中的React.createElement的正确语法(Correct syntax for React.createElement in 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需要动态传递。 有任何想法吗?

I cannot get React.createElement to compile in TypeScript.

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

Component creation:

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

I get this compile error:

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'.

If I remove the constructor, the error goes away. I cannot use the syntax as props needs to be passed dynamically. Any ideas?

最满意答案

当我运行filename.tsx,然后运行node filename.js时,你编写的代码对我来说很好。 是否还有其他代码与此一起?

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

interface IColorPickerProps { name: string, age: number }

接着

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

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

I have solved the problem by upgrading to latest version of React and latest version of the type definitions, this was probably a problem with the type definitions I was using. Thank you all for your help

更多推荐

props,IColorPickerProps,React,'typeof,电脑培训,计算机培训,IT培训"/> <me