【问题标题】:Property 'checked' does not exist on type 'Switch'“开关”类型上不存在“已检查”属性
【发布时间】:2021-01-15 20:34:57
【问题描述】:

我收到来自TypeScriptProperty 'checked' does not exist on type 'Switch'. 消息,用于this.checkedthis.disabled createRefs。另外,在最后一行,我还收到了来自TSProperty 'checked' does not exist on type 'Switch 警告。如何解决这些警告?

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'

【问题讨论】:

  • 如果扩展React.Component 而不是React.PureComponent 会怎样?
  • 没有帮助抱歉
  • 为什么在构造函数签名中使用any作为props类型而不是Props
  • @НиколайГольцев 好收获!

标签: reactjs typescript ref create-ref


【解决方案1】:

您的问题是您需要在将它们与this 一起使用之前定义这些变量。只需定义它们 privatepublic 或您想要的。它的类型将是 React.createRef()React.RefObject 对象的结果。如果您知道将在哪个节点元素上使用ref,那么您可以在类型中精确它。

例如,您在div 上使用this.checked,因此您可以将其定义为React.RefObject&lt;HTMLDivElement&gt;。如果您还不知道,请使用React.RefObject&lt;unknown&gt;

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} />;
  }
}

【讨论】:

  • 太棒了。它要求我为private checked 定义一个类型,我应该将它定义为什么?还是只使用any
猜你喜欢
  • 2018-09-07
  • 2018-10-09
  • 2019-04-21
  • 2019-09-29
  • 1970-01-01
  • 1970-01-01
  • 2023-01-23
  • 2023-03-12
  • 2020-12-11
相关资源
最近更新 更多