为什么TypeScript中Material-ui Button元素的React.createRef无法正常工作?

问题描述

使用React v16.13.1,我具有以下组件类,其中包含Material-UI Button组件和RefObject来访问按钮元素。

class Search extends React.Component<any,any>{

  constructor(props: any) {
    super(props)

    this.streetViewRef = React.createRef();
  }

  private streetViewRef: React.RefObject<Button>;
}

以下按钮元素

<Button ref={this.streetViewRef} size="sm" variant="primary" block >Street View</Button>

但是,将显示以下TypeScript错误

enter image description here

要更正此错误需要更改什么?

解决方法

您需要使用HTMLDivElement创建引用。

createRef<HTMLDivElement>()

所以,这样会更好。

private streetViewRef = createRef<HTMLDivElement>();
,

在这里https://www.selbekk.io/blog/2020/05/forwarding-refs-in-typescript/

键入forwardRef组件的正确方法是:

type Props = {};
const Button = React.forwardRef<HTMLButtonElement,Props>(
  (props,ref) => <button ref={ref} {...props} />
);