簡體   English   中英

State 在 div 的滾動事件處理程序中僅更新一次

[英]State updates only once inside a div's scroll event handler

在我的示例中,有一個可滾動的 div,我嘗試在此 div 的 onscroll 事件中更新 state(只是一個計數器)。 發生的情況是它只更新一次(第一次)。 這是我的示例的工作副本

import React, {useState, useEffect} from 'react';

function App() {

  let divRef = React.createRef();

  const [state, setState] = useState({
    count: 0,
  });

  useEffect(() => {
    divRef.current.addEventListener('scroll', () => {
      setState({
        count: state.count + 1, // this happens only once
      });
    });
  }, []);

  return (
    <div>
      <div style={{position: 'fixed', top: '0'}}>{state.count}</div>
      <div style={{height: '100px', overflow: 'auto'}} ref={divRef}>
        <div style={{height: '1000px'}}></div>
      </div>
    </div>
  );
}

export default App;

如果你想在滾動時更新 state,那么你可以使用 React 提供的onScroll

復制演示

import React, {useState} from 'react';

function App() {

  const [count, setCount] = useState(0);

  const handleScroll = () => {
    setCount(p => p + 1);
  }

  return (
    <div>
      <div style={{position: 'fixed', top: '0'}}>{count}</div>
      <div style={{height: '100px', overflow: 'auto'}} onScroll={handleScroll}>
        <div style={{height: '1000px'}}></div>
      </div>
    </div>
  );
}

export default App;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM