ReactJS - 参考 returns "undefined"

ReactJS - ref returns "undefined"

我正在将 ReactJS 与 NextJS 结合使用。当我尝试设置 ref,我的控制台 returns 我 undefined,这怎么可能?如何解决这个困难?我曾尝试在网上阅读一些命题,但没有成功。

这是我的片段:

 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}>

任何提示都很好, 谢谢

很难从您添加的代码中分辨出来,但您可能只是在构造函数中遗漏了这个命令:

constructor( props ){
    super( props );
    this.handleScroll = this.handleScroll.bind(this)
}

更多信息:https://medium.freecodecamp.org/this-is-why-we-need-to-bind-event-handlers-in-class-components-in-react-f7ea1a6f93eb

createRef返回的对象的current属性是在第一次渲染时设置的,所以如果你在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>