如何在不重新渲染随机放置的同级组件数组的情况下,根据滚动位置更新样式化组件的样式?

How can I update the style of a styled-component based on scroll position without re-rendering an array of randomly placed sibling components?

我有一个执行这些操作的简单组件:

  1. 使用挂钩,设置状态以跟踪 window.scrollY
  2. scroll 事件监听器附加到 window 以更新状态
  3. 创建一个包含 10 个样式组件的数组 - 每个组件都有一个随机分配的 absolute 位置
  4. return/renders 10 个点 另一个样式组件 - 一个三角形,其高度使用步骤 1 中定义的滚动状态计算。
const App = () => {
  // state to keep track of how many px scrolled
  const [scroll, setScroll] = useState(window.scrollY);
  const handleScroll = () => setScroll(window.scrollY);

  // set up listener on window to update scroll state on scroll
  useEffect(() => {
    window.addEventListener("scroll", handleScroll);
  }, []);

  // create 10 dots with random positions
  const dots = [];
  for (let x = 0; x < 10; x++) {
    dots.push(
      <Dot
        key={x}
        topValue={getRandomIntInclusive(1, 199)}
        leftValue={getRandomIntInclusive(1, 99)}
      />
    );
  }

  return (
    <div className="App">
      {dots}
      <Triangle heightValue={scroll / 10} />
    </div>
  );
};

我想要发生的事情

当我向下滚动时,我唯一想要发生的事情是 Triangle 组件高度重新计算/重新渲染。最初渲染的点不会更新或改变。

我的问题

正如您可能猜到的那样,每个滚动事件都会重新呈现这些点,这不仅对性能来说很糟糕,而且会导致每个滚动事件中的点都有一个新的随机位置。

我的问题

  1. 如何让 Triangle 使用更新后的 scroll 值重新渲染,但不让 Dot 组件重新渲染?
  2. 更多的次要问题:如果我还想更新滚动 Dot 组件中的某些样式(例如颜色),但 更新在初始坐骑上创建的随机 topleft 位置,我该怎么做?

我可以用 vanilla JS 很容易地完成这样的事情,但我不太明白 React 的方式。

此问题的完整工作沙箱:https://codesandbox.io/embed/hopeful-greider-jb3td

您需要做的是计算一次点位置并将其保存在一个数组中,这样当滚动位置发生变化时就不会在每次渲染时重新计算它们

您可以将 useEffect 与空 deps 数组一起使用,例如

// main component
const App = () => {
  // state to keep track of how many px scrolled
  const [scroll, setScroll] = useState(window.scrollY);
  const handleScroll = () => setScroll(window.scrollY);
  const [posArr, setPos] = useState([]);
  useEffect(() => {
    const pos = [];
    for (let x = 0; x < 10; x++) {
      pos.push({ topValue: getRandomIntInclusive(1, 199), leftValue: getRandomIntInclusive(1, 99)})
    }
    setPos(pos);
  }, [])
  // set up listener on window to update scroll state on scroll
  useEffect(() => {
    window.addEventListener("scroll", handleScroll);
  }, []);

  // create 10 dots with random positions
  const dots = [];
  for (let x = 0; x < 10; x++) {
    dots.push(
      <Dot
        key={x}
        topValue={posArr[x] && posArr[x].topValue}
        leftValue={posArr[x] && posArr[x].leftValue}
      />
    );
  }

  return (
    <div className="App">
      <br />
      <h2>Scroll to make triangle grow</h2>
      <br />
      <h4>Ideally, the dots would not rerender on scroll</h4>
      <Debug>Px scrolled: {scroll}</Debug>
      {dots}
      <Triangle heightValue={scroll / 10} />
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Working demo

或者使用回调函数初始化状态到useState

// main component
const App = () => {
  // state to keep track of how many px scrolled
  const [scroll, setScroll] = useState(window.scrollY);
  const handleScroll = () => setScroll(window.scrollY);

  // set up listener on window to update scroll state on scroll
  useEffect(() => {
    window.addEventListener("scroll", handleScroll);
  }, []);

  const [posArr, setPos] = useState(() => {
    const pos = [];
    for (let x = 0; x < 10; x++) {
      pos.push({ topValue: getRandomIntInclusive(1, 199), leftValue: getRandomIntInclusive(1, 99) })
    }
    return pos;
  });
  // create 10 dots with random positions
  const dots = [];
  for (let x = 0; x < 10; x++) {
    dots.push(
      <Dot
        key={x}
        topValue={posArr[x].topValue}
        leftValue={posArr[x].leftValue}
      />
    );
  }

  return (
    <div className="App">
      <br />
      <h2>Scroll to make triangle grow</h2>
      <br />
      <h4>Ideally, the dots would not rerender on scroll</h4>
      <Debug>Px scrolled: {scroll}</Debug>
      {dots}
      <Triangle heightValue={scroll / 10} />
    </div>
  );
};

Working demo