简体   繁体   中英

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

Using TypeScript, I have the following props type and component class defined:

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

I want to capture the ref to the div element inside the render function, however I keep getting:

error TS2339: Property 'node' does not exist on type 'AnimatedElement'.

What is the proper way to define and initialise a custom class variable inside a react component using TypeScript?

If I understand your question correctly then this looks like a case of a missing field in your class definition. You should find that declaring the field:

private node?: HTMLElement;

in your class definition resolves the issue:

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

Also note, the node? syntax with question mark. The ? is short hand stating that the field can have type HTMLElement or undefined . This is necessary, seeing that you're initially assigning undefined to the field in your class constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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