【问题标题】:Property 'ref' does not exist on type 'IntrinsicAttributes'类型“IntrinsicAttributes”上不存在属性“ref”
【发布时间】: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 的使用有关,因为这是我第一次使用它,而且我以前从未遇到过此类问题。有谁知道如何解决这个问题?

谢谢!

【问题讨论】:

标签: reactjs typescript typescript-typings typescript-generics react-typescript


【解决方案1】:

复制您的代码时我没有看到任何错误。

但它在运行时确实有 1 个错误:

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 here.

【讨论】:

    猜你喜欢
    • 2021-08-20
    • 2020-01-05
    • 2021-03-17
    • 2019-07-31
    • 2022-12-11
    • 2022-12-30
    • 2020-09-03
    • 2021-04-10
    • 1970-01-01
    相关资源
    最近更新 更多