gpt4 book ai didi

reactjs - 使用 React hooks 和 onScroll 或 onWheel 防止重新渲染

转载 作者:行者123 更新时间:2023-12-04 17:30:18 25 4
gpt4 key购买 nike

我有一个组件,我在其中使用 onWheel 事件来检测所有方向的滚动(这有效)。我的问题是阻止此组件重新呈现,因此我可以利用 underscore.js 中的 throttle :

例子

import React, {useState} from 'react';
import { throttle } from 'underscore';

const App = () => {
const [position, setPosition] = useState({x: 0, y: 0});
const updatePosition = throttle((e) => {
e.preventDefault(); // Required for left/right swiping.

setPosition({
x: position.x + e.deltaX,
y: position.y + e.deltaY,
});
}, 1000);

return (
<div className="viewport" onWheel={updatePosition}>
<Box x={position.x} y={position.y} />
</div>
);
};

export default App;

throttle 函数在这里不起作用,因为每次状态更新时组件都会重新渲染。

最佳答案

你能试试下面的吗?我只是用新功能包裹了 throttle 。

import { throttle } from "underscore";

import Box from "./Box";

const App = () => {
const [position, setPosition] = useState({ x: 0, y: 0 });

function updatePosition(e) {
e.preventDefault(); // Required for left/right swiping.

throttle(e => {
setPosition({
x: position.x + e.deltaX,
y: position.y + e.deltaY
});
}, 1000)(e);
}

return (
<div className="viewport" onWheel={updatePosition}>
<Box posX={position.x} posY={position.y} />
</div>
);
};

export default App;

Edit gifted-sun-i9ism

关于reactjs - 使用 React hooks 和 onScroll 或 onWheel 防止重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60363996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com