簡體   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