我有以下HOC:
function isComponentClass(Component: React.ComponentClass) {
return Component.prototype.render;
}
export const withShortcuts = function<T>(createShortcuts: CreateShortcuts) {
return (Component: React.ComponentClass<T> | React.StatelessComponent<T>) => {
class WrappedShortcuts extends React.Component<T> {
ref: React.RefObject<T>;
constructor(props: T) {
super(props);
this.ref = React.createRef();
}
render() {
return (
<Shortcuts createShortcuts={createShortcuts}>
{isComponentClass(Component) ? <Component ref={this.ref} {...this.props} /> : <Component {...this.props} />}
</Shortcuts>
);
}
}
return hoistStatics(WrappedShortcuts, Component);
};
};
问题是isComponentClass
是不允许TS编译器知道我可以在类中添加ref
时出现错误并且我收到错误:
财产&#39; ref&#39;类型&#39; IntrinsicAttributes&amp; { 孩子?:ReactNode; }&#39;
答案 0 :(得分:1)
您需要将isComponentClass
更改为类型保护。类型保护功能是一种在if或?:
中使用时更改传递给它的参数类型的函数。详细了解类型警卫here:
function isComponentClass<T>(Component: React.ComponentClass<T> | React.StatelessComponent<T>) : Component is React.ComponentClass<T> {
return Component.prototype.render;
}
isComponentClass(Component) ?
<Component ref={this.ref} {...this.props} /> : // Component is React.ComponentClass<T> here
<Component {...this.props} /> // Component is React.StatelessComponent<T> here