最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ReactJS - ref returns "undefined" - Stack Overflow

programmeradmin1浏览0评论

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:

 ponentDidMount() { 
        this.myRef = React.createRef();
        window.addEventListener('scroll', this.handleScroll, { passive: true })
      }

      ponentWillUnmount() {
        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

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:

 ponentDidMount() { 
        this.myRef = React.createRef();
        window.addEventListener('scroll', this.handleScroll, { passive: true })
      }

      ponentWillUnmount() {
        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

Share Improve this question asked Nov 24, 2018 at 19:25 Diagathe JosuéDiagathe Josué 12.1k14 gold badges49 silver badges93 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 5

The current property of the object returned from createRef is set on the first render, so if you create it in the ponentDidMount after the ponent has been rendered it will not be set.

You also have to bind the handleScroll method, or this will not be what you expect.

Example

class App extends React.Component {
  myRef = React.createRef();

  ponentDidMount() {
    window.addEventListener("scroll", this.handleScroll, { passive: true });
  }

  ponentWillUnmount() {
    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./react@16/umd/react.development.js"></script>
<script src="https://unpkg./react-dom@16/umd/react-dom.development.js"></script>
  
<div id="root"></div>

It's difficult to tell from the code you added, but you might be simply missing this imperative in your constructor:

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

more info: https://medium.freecodecamp/this-is-why-we-need-to-bind-event-handlers-in-class-ponents-in-react-f7ea1a6f93eb

发布评论

评论列表(0)

  1. 暂无评论