我遇到了有关接口和Typescript的问题 . 以下示例:import * as React from“react”;
/*
* An interface used to describe the properties of the react component.
*/
interface IUnsafeComponentProps {
component: IUnsafeComponent //& typeof React.Component;
}
/*
* An interface used to describe every component that is allowed to be rendered.
* It needs to define a property called "componentName".
*/
export interface IUnsafeComponent {
componentName: string;
componentStyles?: {};
}
/*
* The React component itself used to render the unsafe component.
*/
export class UnsafeComponent extends React.Component<IUnsafeComponentProps, any> implements IUnsafeComponent {
public componentName: string;
constructor(props: IUnsafeComponentProps) {
super(props);
this.componentName = "UnsafeComponent";
}
public render(): JSX.Element {
return <this.props.component/>;
}
}
这种包装器的原因是允许在我的应用程序中呈现第三方代码 . 如果我现在尝试使用该组件:
let content = <UnsafeComponent component={UnsafeComponent}/>;
ReactDOM.render(content, document.getElementById("root"));
我收到以下错误消息:
类型'typeof UnsafeComponent'不能分配给'IUnsafeComponent'类型 . [0]类型'typeof UnsafeComponent'中缺少属性'componentName' .
我真的不知道为什么我的ddeclaraion是错的 . 我对Typescript / Javascript很新 . 也许我在这里得到一些非常基本的错误 .
1 回答
这个声明说你想要一个
IUnsafeComponent
的实例:在这里,您传递了
UnsafeComponent
的构造函数:你可能想要的是这个,它说你想要一些产生
IUnsafeComponent
的构造函数:另请参阅What does the error "JSX element type '...' does not have any construct or call signatures" mean?,其中讨论了JSX组件引用如何与类构造函数相关,而不是类实例 .