简体   繁体   中英

$(this) inside React Component

I am trying to change the url while scrolling the page.

I am using jQuery .scroll() for that. The problem is that this on $(this) grabs the context of the React component. How can I change this code to make it work?

import React from 'react';
import $ from 'jquery';

class Main extends React.Component {
  componentDidMount() {
    $(() => {
      let currentId = 'about';

      $(document).scroll(() => {
        $('.path').each(() => {
          const top = window.pageYOffset;
          const distance = top - $(this).offset().top;
          const path = $(this).attr('id');

          if (distance < 50 && distance > -50 && currentId !== path) {
            window.history.pushState(null, null, '/' + path);
            currentId = path;
          }
       });
      });
     }); 
  }

 render() {
     return (
       <main role="main">
         <About />
         <Contact />
       </main>
     );
   }
 }


export default Main;

The error: 在此处输入图片说明

Just as a complement, I am following these 'helpers' and adapt them to my needs:

Just use normal function when you need dynamic context

$('.path').each(function() {
          const top = window.pageYOffset;
          const distance = top - $(this).offset().top;
          const path = $(this).attr('id');

          if (distance < 50 && distance > -50 && currentId !== path) {
            window.history.pushState(null, null, '/' + path);
          }
       });

So, the solution is the accepted answer . The problem had to do with the way I was adding the anonymous function as a parameter for the .each() method. Instead of () => {...} , use function(){...} .

$(() => {
      let currentPath = '';
      $(document).scroll(() => {
        $('.path').each(function () {
          const top = window.pageYOffset;
          const distance = top - $(this).offset().top;
          const path = $(this).attr('id');

          if (distance < 30 && distance > -30 && currentPath != path) {
            window.history.replaceState(`/${path}`, 'Title', `/${path}`);
            currentPath = path;
          }
        });
      });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM