类型“ Switch”上不存在“已检查”属性

时间:2020-09-30 07:42:57

标签: reactjs typescript ref create-ref

我从Property 'checked' does not exist on type 'Switch'.收到TypeScriptthis.checked createRefs的this.disabled消息。另外,在最后一行,我还收到来自Property 'checked' does not exist on type 'Switch的{​​{1}}警告。如何解决这些警告?

TS

1 个答案:

答案 0 :(得分:0)

您的问题是,您需要先定义此变量,然后将它们与this一起使用。只需定义它们privatepublic或您想要的内容即可。它的类型将是React.createRef()对象React.RefObject的结果。如果知道要在哪个节点元素上使用ref,则可以在类型中对其进行精确调整。

例如,您在this.checked上使用div,因此可以像React.RefObject<HTMLDivElement>那样定义它。如果您还不知道,请使用React.RefObject<unknown>

export default class Switch extends React.PureComponent<Props, States> {
  private checked: React.RefObject<HTMLDivElement>;
  private disabled: React.RefObject<unknown>;

  constructor(props: any) {
    super(props);
    this.checked = React.createRef(); // comment this line out to use as controlled component
    this.disabled = React.createRef(); // comment this line out to use as controlled component
    this.state = {
      checked: false,
      disabled: false
    };
  }

  render() {
    return <div ref={this.checked} />;
  }
}

Edit lucid-galileo-neckr

相关问题