I have a universal React + Redux app which render the first screen page on server side, then the browser side ReactJS will finish the rest of tasks.
Currently I met an issue, I can't access the refs using
1. this.refs[xxx]
2. 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());
}
}
I need get the ReactDom element while user is scrolling the page and do some thing on that element. But if I can only access refs in componentDidMount(), how can I make this happen?
Thanks.
Try debugging, put a breakpoint in handleScroll to check what all you get in 'this'. Can you see any other refs, or state?
You can try binding 'this' to handleScroll, if that helps, like:
window.addEventListener('scroll', this.handleScroll.bind(this));