我在 .tsx 文件中使用 Typescript 和 Material-ui 编写 ReactJS 类。在我的一个自定义组件中,我想创建一个对我在我的自定义组件中使用的组件之一的引用。
export class MyTextField extends React.Component<MyProps, MyState> {
private refTextField: React.RefObject<TextField>;
constructor(props: MyProps) {
super(props);
this.refTextField = React.createRef();
}
render(): JSX.Element {
const { id, label, value: defaultValue } = this.props;
const { value } = this.state;
const element = (
<TextField ref={this.refTextField} id={id} label={label} defaultValue={defaultValue} value={value} />
);
return element;
}
}
在编译期间,我的引用声明出现错误:
'TextField' refers to a value, but is being used as a type here. TS2749
我试图在我的声明中加入“typeof TextField”,但在我的渲染中评估 ref 属性时,我还有另一条消息:
Type 'RefObject<(props: TextFieldProps) => Element>' is not assignable to type '((instance: HTMLDivElement | null) => void) | RefObject | null | undefined'. Type 'RefObject<(props: TextFieldProps) => Element>' is not assignable to type 'RefObject'. Type '(props: TextFieldProps) => Element' is missing the following properties from type 'HTMLDivElement': align, addEventListener, removeEventListener, accessKey, and 238 more. TS2322
有任何想法吗 ?
太感谢了
最佳答案
确保您使用的是 .tsx
文件而不是 .ts
文件
关于ReactJS 和 Typescript : refers to a value, 但在此处用作类型 (TS2749),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62059408/