react useCallback获取元素实时高度

import React, { useCallback, useState } from 'react';
import { Button } from 'antd';
const maxHeight = 540;
const Component = () => {
    const [textHeight, setTextHeight] = useState(22);
    const [text, setText] = useState('文本元素');
    const [resizeFF, setResizeFF] = useState({});
    const textEl = useCallback(
        (node) => {
            if (node !== null) {
                setTextHeight(node.getBoundingClientRect().height);
            }
        },
        [resizeFF]
    );
    return (
        <div style={{ width: '10em', margin: '30px auto' }}>
            <div
                ref={textEl}
                style={{ width: '10em', maxHeight, overflow: 'auto', border: '1px solid blue' }}
            >
                {text}
            </div>
            <div>当前的高度是:{textHeight}</div>
            <div>最大高度:{maxHeight}</div>
            <Button
                onClick={() => {
                    setText(text.repeat(5));
                    setResizeFF({});
                }}
                disabled={textHeight >= maxHeight}
                type="primary"
            >
                点击获取高度
            </Button>
        </div>
    );
};
export default Component;
posted @ 2023-05-05 14:07  橙云生  阅读(217)  评论(0编辑  收藏  举报