0

我有一个通用的 React + Redux 应用程序,它在服务器端呈现第一个屏幕页面,然后浏览器端 ReactJS 将完成其余任务。

目前我遇到了一个问题,我无法使用 1. this.refs[xxx] 2 访问 refs。ref={(ref) => this.xxx = ref}

componentDidMount() {
    // The code in handleScroll cannot get this.xxx, as it would print the error 
    // Uncaught TypeError: Cannot read property 'xxx' of null
    window.addEventListener('scroll', this.handleScroll);
    // Code below can get the rect numbers.
    console.log(this.xxx.getBoundingClientRect());
}

handleScroll(event) {
   if (this.xxx !== null) {
     console.log(this.xxx.getBoundingClientRect());
   }
 }

我需要在用户滚动页面并对该元素执行某些操作时获取 ReactDom 元素。但是如果我只能访问 componentDidMount() 中的 refs,我该如何实现呢?

谢谢。

4

1 回答 1

0

尝试调试,在 handleScroll 中放置一个断点来检查你在“this”中得到了什么。你能看到任何其他的裁判或状态吗?

如果有帮助,您可以尝试将“this”绑定到 handleScroll,例如:

window.addEventListener('scroll', this.handleScroll.bind(this));
于 2016-10-13T11:27:21.740 回答