首页 > 解决方案 > 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

标签: javascriptreactjspositionref

解决方案


从返回的对象的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>


推荐阅读