使用挂钩在调整大小时测量React DOM节点

时间:2019-10-21 09:14:58

标签: javascript reactjs react-hooks

我正在尝试在窗口调整大小事件上测量React DOM节点。我已经在React hooks-faq上使用了示例,但是它仅在第一个渲染中发生。如果我添加useEffect来监听调整大小,是否不会调用该回调?

function MeasureExample() {
    const [height, setHeight] = useState(0);

    const measuredRef = useCallback(node => {
        if (node !== null) {
            setHeight(node.getBoundingClientRect().height);
        }
    }, []);


    // Adding this effect doesn't re-calculate the height???
    useEffect(() => {

        window.addEventListener("resize", measuredRef);

        return (): void => {
            window.removeEventListener("resize", measuredRef);
        };

    }, [height])

    return (
        <>
            <h1 ref={measuredRef}>Hello, world</h1>
            <h2>The above header is {Math.round(height)}px tall</h2>
        </>
    );
}

3 个答案:

答案 0 :(得分:1)

我个人将提取侦听调整大小事件的部分。优点是可以再次用于其他用途。

因为调整大小为async,所以React的一个窍门是使子级返回功能返回,而不仅仅是返回JSX。然后,您可以让CaptureResize组件调用该函数来获取它的JSX,同时将大小传递给该函数。

下面是一个例子。

const {useLayoutEffect, useRef, useState} = React;

function CaptureResize(props) {
  const {captureRef} = props;
  function updateSize() {
    setSize(captureRef.current.getBoundingClientRect());
  }
  useLayoutEffect(() => {
    updateSize();
    window.addEventListener("resize", updateSize);
    return () => 
      window.removeEventListener("resize", updateSize);
  }, []);
  const [size, setSize] = useState({});
  return props.children(size)
}

function Test() {
  const c = useRef(null);
  return <CaptureResize captureRef={c}>
    {(size) => <React.Fragment>
      <h1 ref={c}>Header 1, Resize window to make this go onto diffrent no. of lines</h1>
      <div>height of header = {size.height}px</div>
    </React.Fragment>}
  </CaptureResize>;
}

ReactDOM.render(<React.Fragment>
  <Test/>
</React.Fragment>, document.querySelector('#mount'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="mount"></div>

答案 1 :(得分:1)

测量窗口屏幕尺寸,并使用反应钩子调整大小

df1=pd.read_csv('https://cocl.us/sanfran_crime_dataset')
df1.drop(df1.columns.difference(['PdDistrict']),1,inplace=True)
df1=df1.rename(columns={'PdDistrict':'Neighborhood'})
df1['Counts']=df1.groupby('Neighborhood')['Neighborhood'].count() 
df1

答案 2 :(得分:0)

这是另一种解决方案。

function MeasureExample() {
    const [height, setHeight] = useState(0);
    const [node, setNode] = useState(null);

    const measuredRef = useCallback(node => {
        if (node !== null) {
            setNode(node);
        }
    }, []);


    // Adding this effect doesn't re-calculate the height???
    useLayoutEffect(() => {
        if(node){
         const measuer = () => {
           setSize(node.getBoundingClientRect().height);
         }
        
         window.addEventListener("resize", measuer );

         return () => {
           window.removeEventListener("resize", measuer );
         };
       }
    }, [node])

    return (
        <>
            <h1 ref={measuredRef}>Hello, world</h1>
            <h2>The above header is {Math.round(height)}px tall</h2>
        </>
    );
}