[嗨,我是Typescript的新手,目前正在为如何键入包含HTML标签或react组件的prop感到困惑。这是我的代码
export interface MyProps {
component: string | HTMLElement;
}
class MyComponent extends React.PureComponent<MyProps, State> {
render() {
const Component = this.props.component;
return <Component ...>...</Component>
}
}
用法:
<MyComponent component={({children}) => children} /> // any functional or class component
<MyComponent component="div" /> // any html tag div, svg...
我得到的错误:
semantic error TS2604: JSX element type 'Component' does not have any construct or call signatures
基本上,我在尝试提供实际的React / Html元素来创建组件或字符串时遇到了一个错误。这将无法实现您的实现方式,因此,我的第一个解决方案是删除字符串,而仅使用诸如</div>, </h1>, </YourComponent>
之类的元素并使Props像这样。
export interface MyProps {
component: React.ComponentClass | HTMLElement;
}
但是,如果您真的想将该字符串保留为选项之一,则需要实现React.createElement(component,props)函数,该函数应该执行您想要的操作