我有一个组件,我在其中使用onWheel事件来检测所有方向的滚动(这是有效的)。我的问题是阻止这个组件重新渲染,这样我就可以利用来自underscore.js的节流:
示例
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;
节流函数在这里不起作用,因为每次状态更新时,组件都会重新呈现。
发布于 2020-02-23 15:59:46
你能试试下面这个吗?我刚刚用新的函数控制住了油门。
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;
发布于 2020-02-23 18:12:35
您可以通过创建一个名为ThrottledBox
的新组件,使用下划线中的throttle
函数限制组件的呈现。
export default function App() {
const [position, setPosition] = React.useState({ x: 0, y: 0 });
function handleOnWheen(e) {
e.preventDefault(); // Required for left/right swiping.
setPosition({
x: position.x + e.deltaX,
y: position.y + e.deltaY
});
}
return (
<div className="viewport" onWheel={handleOnWheen}>
<ThrottledBox x={position.x} y={position.y} />
</div>
);
}
const ThrottledBox = throttle((props) => <Box {...props}/>, 1000);
https://stackoverflow.com/questions/60363996
复制