为什么TypeScript中针对Material-ui Button元素的React.createRef()无法正常工作? [英] Why does React.createRef() for material-ui Button element in TypeScript not work correctly?
本文介绍了为什么TypeScript中针对Material-ui Button元素的React.createRef()无法正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用React v16.13.1,我具有以下组件类,其中包含Material-UI Button组件和RefObject来访问按钮元素.
Using React v16.13.1 I have the following component class with a Material-UI Button component and a RefObject to access the button element.
class Search extends React.Component<any, any>{
constructor(props: any) {
super(props)
this.streetViewRef = React.createRef();
}
private streetViewRef: React.RefObject<Button>;
}
对于以下Button元素
for the following Button element
<Button ref={this.streetViewRef} size="sm" variant="primary" block >Street View</Button>
但是,将显示以下TypeScript错误.
However, the following TypeScript error is displayed.
要更正此错误需要更改什么?
What needs to be changed to correct this error?
推荐答案
The correct way to type a forwardRef component is:
type Props = {};
const Button = React.forwardRef<HTMLButtonElement, Props>(
(props, ref) => <button ref={ref} {...props} />
);
这篇关于为什么TypeScript中针对Material-ui Button元素的React.createRef()无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文