我正在做一个React类型脚本项目。代码有效,但ts编译器一直在抱怨我的参考。以下是代码:
首先,我有一个高阶组件来处理错误:
export class ErrorBoundary extends React.Component<ErrorBoundaryProps> {
constructor(props: ErrorBoundaryProps) {
super(props);
}
static getDerivedStateFromError(error: any) {
// some error handling related code
}
public componentDidCatch(error: any) {
// some error handling related code
}
public render() {
return this.props.children;
}
}
还有一个高阶组件:
export function withErrorBoundary<T = {}>(Component: React.ComponentType<T>): React.ComponentType<T> {
function Wrapped(props: T) {
return (
<ErrorBoundary>
<Component {...props} />
</ErrorBoundary>
);
}
return Wrapped;
}
这样做效果很好:const NewComponent = withErrorBoundary(MyComponent)
但现在我正在构建一个需要React.forwardRef
:的新组件
interface ILabelProps {
value: string;
mark: boolean;
// other props with basic types
}
export const Label = React.forwardRef(
(props: ILabelProps, ref) => {
React.useImperativeHandle(ref, () => ({
// some custom logic
}), []);
return (
<>{...my UI}</>
);
});
export MyLabel = withErrorBoundary(Label);
然而,当我这样使用它时,它会错误地引用:
类型"IntrnsicAttributes&ILabelProps的
const App = () => {
const labelRef = React.useRef();
return <MyLabel {...props} ref={labelRef} />
}
然而,如果我只使用Label
而不使用errorBoundary
HOC,它就会停止抱怨:
const App = () => {
const labelRef = React.useRef();
return <Label {...props} ref={labelRef} />
}
我认为这个问题可能与React.forwardRef
的使用有关,因为这是我第一次使用它,我以前从未遇到过这种问题。有人知道怎么解决这个问题吗?
谢谢!
复制您的代码时,我没有看到任何错误。
但它在运行时确实有一个错误:
Warning: Function components cannot be given refs.
Attempts to access this ref will fail.
Did you mean to use React.forwardRef()?
基本上,您的组件MyLabel = withErrorBoundary(Label)
是从withErrorBoundaray
返回的新组件,因此它丢失了Label
提供的forwardRef
。要修复此问题,您只需要将labelRef
传递给Label
组件,如下所示:
const MyLabel2 = withErrorBoundary(() => <Label {...props} ref={labelRef} />);
此处为Codesandbox。