【发布时间】: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)而你只能<ColorPicker/>? -
因为 props 作为参数动态传递给创建 ColorPicker 的类。
<ColorPicker myProp={props["name"]}/>会丢失编译时间检查,而React.createElement(ColorPicker, props)不会。
标签: reactjs typescript jsx