ReactJS 和 Typescript : refers to a value, 但在此处用作类型 (TS2749)

标签 reactjs typescript validation material-ui tsx

我在 .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/

相关文章:

javascript - 如何将 div contenteditable = "false"更改为 "true"?

angular - 为 Angular 配置 Jest

jquery - 使用 jquery 验证电话号码

css - 在 React 中使用 CSS Peek

javascript - React JSX - 以粗体显示子字符串

node.js - 在 mongoose .d.ts 中分配自定义方法,这样我就可以在 typescript 中使用 mongoose 的任何地方使用它们

xml - 使用 dtd 时 clojure xml 解析缓慢

python - Django:构造表单而不验证字段?

javascript - 使用 redux-form 异步加载数据不起作用

javascript - 如何在爱彼迎 react 日期中选择小时/分钟