0

我收到Property 'checked' does not exist on type 'Switch'.来自TypeScriptforthis.checkedthis.disabledcreateRefs 的消息。此外,在最后一行,我也收到了Property 'checked' does not exist on type 'Switch来自TS. 如何修复这些警告?

interface Props {
  checked: boolean;
  onChange: (checked: boolean) => void;
  disabled?: boolean;
}

interface States {
  checked: boolean;
  disabled?: boolean;
}

export default class Switch extends React.PureComponent<Props, States> {
  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() {
    ...
    <div ref={this.checked}> // TypeScript warns: Property 'checked' does not exist on type 'Switch'
4

1 回答 1

0

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

例如,您this.checked在 a 上使用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} />;
  }
}

编辑 lucid-galileo-neckr

于 2020-09-30T07:53:19.890 回答