【发布时间】:2021-08-23 00:33:03
【问题描述】:
我正在开发一个 React 打字稿项目。代码有效,但 ts 编译器一直抱怨我的 ref。代码如下:
首先我有一个高阶组件来处理错误:
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);
但是当我这样使用它时,它会出错:
“IntrinsicAttributes & ILabelProps”类型上不存在属性“ref”
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 的使用有关,因为这是我第一次使用它,而且我以前从未遇到过此类问题。有谁知道如何解决这个问题?
谢谢!
【问题讨论】:
-
你需要为要转发的
ref指定一个类型,但是I'm not seeing the error。
标签: reactjs typescript typescript-typings typescript-generics react-typescript