简体   繁体   English

State 在 div 的滚动事件处理程序中仅更新一次

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

In my example there is a scrollable div and I try to update the state (just a counter) inside onscroll event of this div.在我的示例中,有一个可滚动的 div,我尝试在此 div 的 onscroll 事件中更新 state(只是一个计数器)。 What happens is it updates only once (the first time).发生的情况是它只更新一次(第一次)。 This is working repl of my example. 这是我的示例的工作副本

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;

If you want to update state on scroll then you can use onScroll provided by React.如果你想在滚动时更新 state,那么你可以使用 React 提供的onScroll

Repl-demo 复制演示

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