[英]$(this) inside React Component
我正在尝试在滚动页面时更改URL。
我为此使用jQuery .scroll()。 问题是, this
在$(this)
抓住做出反应组件的上下文。 如何更改此代码以使其正常工作?
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;
作为补充,我正在关注这些“帮助者”,并使其适应我的需求:
此问题的可接受答案: 手动滚动到锚点时更改url?
这个jsfiddle: jsfiddle
仅在需要动态上下文时使用常规功能
$('.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);
}
});
因此, 解决方案是公认的答案 。 问题与我将匿名函数添加为.each()
方法的参数的方式有关。 代替() => {...}
,使用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.