[英]$(this) inside React Component
I am trying to change the url while scrolling the page. 我正在尝试在滚动页面时更改URL。
I am using jQuery .scroll() for that. 我为此使用jQuery .scroll()。 The problem is that
this
on $(this)
grabs the context of the React component. 问题是,
this
在$(this)
抓住做出反应组件的上下文。 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;
Just as a complement, I am following these 'helpers' and adapt them to my needs: 作为补充,我正在关注这些“帮助者”,并使其适应我的需求:
The accepted answer for this question: Change url when manually scrolled to an anchor? 此问题的可接受答案: 手动滚动到锚点时更改url?
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. 问题与我将匿名函数添加为
.each()
方法的参数的方式有关。 Instead of () => {...}
, use function(){...}
. 代替
() => {...}
,使用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;
}
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.