简体   繁体   English

在 class 组件方法中使用 refs

[英]Using refs within class component methods

How do I access refs within different methods of one component?如何在一个组件的不同方法中访问 refs? As the example below, I am trying to access a node through a reference within a method, not the render() function, which results Uncaught TypeError: Cannot read property 'current' of undefined at handleScroll .如下例所示,我试图通过方法中的引用访问节点,而不是render() function,这会导致Uncaught TypeError: Cannot read property 'current' of undefined at handleScroll Ideas?想法?

Constructor:构造函数:

constructor(props) {
  super(props);
  this.parallaxHeaderRef = createRef();

this.renderWelcomeMessage = this.renderWelcomeMessage.bind(this);
this.renderMenu = this.renderMenu.bind(this);
this.renderHeroBackground = this.renderHeroBackground.bind(this);
}

Binding method to didMount(): didMount() 的绑定方法:

componentDidMount() {
  window.addEventListener('scroll', this.handleScroll);
}

Accessing ref within another method:在另一种方法中访问 ref:

handleScroll() {
  const currentScrollPos = window.pageYOffset;
  const node = this.parallaxHeaderRef.current;

  if (window.innerWidth > 700) {
    node.style.transform = `translateY(${currentScrollPos / 16}px)`;
  }
}
renderWelcomeMessage() {
  <h2 ref={this.parallaxHeaderRef}></h2>
}

Render:使成为:

render() {
    return (
      <div className="hero" id="hero">
        { this.renderWelcomeMessage() }
        { this.renderMenu() }
        { this.renderHeroBackground() }
      </div>
    );
  }
}

How do I access refs within different methods of one component?如何在一个组件的不同方法中访问 refs? As the example below, I am trying to access a node through a reference within a method, not the render() function, which results Uncaught TypeError: Cannot read property 'current' of undefined at handleScroll .如下例所示,我试图通过方法中的引用访问节点,而不是render() function,这会导致Uncaught TypeError: Cannot read property 'current' of undefined at handleScroll Ideas?想法?

Constructor:构造函数:

constructor(props) {
  super(props);
  this.parallaxHeaderRef = createRef();

this.renderWelcomeMessage = this.renderWelcomeMessage.bind(this);
this.renderMenu = this.renderMenu.bind(this);
this.renderHeroBackground = this.renderHeroBackground.bind(this);
}

Binding method to didMount(): didMount() 的绑定方法:

componentDidMount() {
  window.addEventListener('scroll', this.handleScroll);
}

Accessing ref within another method:在另一种方法中访问 ref:

handleScroll() {
  const currentScrollPos = window.pageYOffset;
  const node = this.parallaxHeaderRef.current;

  if (window.innerWidth > 700) {
    node.style.transform = `translateY(${currentScrollPos / 16}px)`;
  }
}
renderWelcomeMessage() {
  <h2 ref={this.parallaxHeaderRef}></h2>
}

Render:使成为:

render() {
    return (
      <div className="hero" id="hero">
        { this.renderWelcomeMessage() }
        { this.renderMenu() }
        { this.renderHeroBackground() }
      </div>
    );
  }
}

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

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