繁体   English   中英

由于错误组件内部错误“ TS2339:类型'Y'上不存在属性'X'”,因此无法设置参考

[英]Unable to set ref due to error “TS2339: Property 'X' does not exist on type 'Y' ” inside a react component

使用TypeScript,我定义了以下道具type和组件class

type AnimatedElementProps = {
  node: HTMLElement;
  Svg(props: SVGProps): JSX.Element,
 };

class AnimatedElement extends React.Component<AnimatedElementProps> {

  constructor(props) {
    super(props);
    this.node = undefined;
  }

  render = () => {
    return (
          <div
              ref={(n) => this.node = n}
              className={styles.animatedElement}
              style={defaultStyle}
          >
            <Svg/>
          </div>
    );
  };
}

我想在render函数中捕获对div元素的ref ,但是我不断得到:

错误TS2339:类型“ AnimatedElement”上不存在属性“节点”。

使用TypeScript在React组件中定义和初始化自定义类变量的正确方法是什么?

如果我正确理解了您的问题,那么这似乎是您的类定义中缺少字段的情况。 您应该发现在声明该字段:

private node?: HTMLElement;

在您的班级定义中解决了这个问题:

class AnimatedElement extends React.Component<AnimatedElementProps> {

  private node?: HTMLElement; /* <-- Add this */

  constructor(props) {
    super(props);
    this.node = undefined;
  }

  render = () => {
    return (
          <div
              ref={(n) => this.node = n}
              className={styles.animatedElement}
              style={defaultStyle}
          >
            <Svg/>
          </div>
    );
  };
}

还要注意, node? 带问号的语法。 ? 是简短说明,该字段可以具有HTMLElement类型或undefined 看到您最初是在类构造函数中为该字段分配undefined时,这是必要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM