[英]$(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.