【问题标题】:Missing ref node on resize event调整大小事件时缺少 ref 节点
【发布时间】:2016-08-21 08:37:46
【问题描述】:

我尝试在 resize 事件上调用“setHolePosition”方法,但是 this.hole 是空的,但第一次可以正常工作。当我调整窗口大小时,console.log 显示空数组,我不明白为什么?以及我可以在 React App 中存储 refs 的位置

import React, {Component} from 'react';
import $ from 'jquery';

import './indexPageStyles.sass';

class IndexPageComponent extends Component {
  showHole() {
    setTimeout(() => {
      this.hole.addClass('hole--visible');
      this.setHolePosition();
    }, 1000)
  }
  setHolePosition(){

    const doc = $(document);
    let dh = doc.height();
    let dw = doc.width();

    console.log(this.hole);

    this.hole.css({
      top: dh / 2 - $(this.hole).height() / 2,
      left: dw / 2 - $(this.hole).width() / 2
    });


    // TODO: unbind this listener
    window.addEventListener('resize', this.setHolePosition);
  }

  render() {
    return (
      <div className="indexPage">
        <div className="hole" ref={(hole) => {
          this.hole = $(hole);
          this.showHole();
        }}></div>
      </div>
    )
  }
}

export default IndexPageComponent;

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    忘记绑定到组件的方法。 this.setHolePosition = this.setHolePosition.bind(this);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      相关资源
      最近更新 更多