javascript - ReactJS - ref returns "undefined"
问题描述
I'm using ReactJS with NextJS. When I'm trying to set a ref
, my console returns me undefined
, how it is possible? How remedy to this difficulty? I have tried to read some propositions on the web but without success.
Here my snippet:
componentDidMount() {
this.myRef = React.createRef();
window.addEventListener('scroll', this.handleScroll, { passive: true })
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll)
}
handleScroll(e) {
e.preventDefault();
// let offsetTop = this.myRef.current.offsetTop;
// here I'm trying just a console.log to preview the value
// otherwise my program will just crash
console.log("I'm scrolling, offsetTop: ", this.myRef)
}
render() {
return (
<div className={style.solution_container_layout} >
<div ref={this.myRef} className={style.solution_item}>
Any hint would be great, thanks
解决方案
从返回的对象的current
属性createRef
是在第一次渲染时设置的,因此如果您在componentDidMount
组件渲染后创建它,它将不会被设置。
您还必须绑定该handleScroll
方法,否则this
将不会是您所期望的。
例子
class App extends React.Component {
myRef = React.createRef();
componentDidMount() {
window.addEventListener("scroll", this.handleScroll, { passive: true });
}
componentWillUnmount() {
window.removeEventListener("scroll", this.handleScroll);
}
handleScroll = () => {
console.log("I'm scrolling", this.myRef.current);
};
render() {
return <div ref={this.myRef} style={{ height: 1000 }}> Scroll me </div>;
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
推荐阅读
- html - Flex box - 一个大 div 紧挨着几个小 div
- android - Ionic Capacitor Cordova YouTube Video Player 在 Android 项目中声明 YouTubeDataApiKey 的位置
- javascript - preact-cli/babel/typescript - 让 Symbol.iterator 和 [...spread] 正常工作
- flutter - 我真的,甚至不知道如何为这个问题提出问题
- java - PreAuthorize 在 Spring Security 中不起作用
- python - Python 3 从体育网站提取 html 数据
- python - “索引 14 超出轴 0 的范围,大小为 2”
- c# - ASP.NET core OData:将包含字典的类序列化为 JSON,字典变成键值对数组。需要它是一个对象
- c# - 以窗口形式显示来自 CLIPS 的信息
- python - 如何在python中异步运行http请求