使用React钩子和onScroll或onWheel防止重新渲染

时间:2020-02-23 15:49:59

标签: reactjs react-hooks

我有一个组件,在该组件中,我使用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;

节气门功能在这里不起作用,因为每次状态更新时都会重新渲染组件。

2 个答案:

答案 0 :(得分:1)

您可以尝试以下一种吗?我只是用新功能包裹了油门。

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

答案 1 :(得分:0)

您可以使用throttle函数通过下划线创建一个名为ThrottledBox的新组件来限制组件的渲染。

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://codesandbox.io/s/zealous-booth-x8lfd

相关问题