一个滚动框高度动态计算解决方案

需求描述,一个嵌套了很多层div或者其他标签的内容框,而它的外层没有设置高度,或者使用百分比,而本容器需要设置高度来实现滚动,要么写死px高度,但是不能自适应,此时需要一个直系父容器(该容器要动态计算高度)包裹,这里的解决方法是,设计一个高阶方法,用于给本容器增加一个计算高度的父容器,并且超出高度隐藏内容。

php 复制代码
// 自定义高阶函数
// customizeHeightWrap.tsx"
import React, { useEffect, useState } from 'react';


export const customizeHeightWrap = (MyComponent: React.ComponentType<any>, minusHeight?: number) => {
// MyComponent为需要包裹的组件,minusHeight为参照父组件高度需要减去的高度(得到要滚动的高度)
    return function(props:any) {
        const [customHeight, setCustomHeight] = useState(500);
        useEffect(() => {
            window.addEventListener('resize', () => getClientHeight()); 
            getClientHeight(); 
            return () => {
            // 移除监听
            window.removeEventListener('resize', getClientHeight);
            };
        }, [])

        const getClientHeight = () => {
            try {
            const clientHeight = document.documentElement.clientHeight; // document.body.clientHeight
            const setHeight = clientHeight - (minusHeight || 0)
            setCustomHeight(setHeight);
            } catch (error) {}
        };
        return (
            <div className="customizeHeightWrap" style={{height: customHeight, overflowY: 'hidden'}}>
                <MyComponent {...props} />
            </div>
        );
    };
}
php 复制代码
// ScrollComponent.tsx 需要设置滚动的容器
import React, { useEffect, useState } from 'react';
import type { FC } from 'react';
import { customizeHeightWrap } from "@/components/customizeHeightWrap.tsx"
interface IProps = {
xxx: string;
...
}

const ScrollComponent: FC<IProps> = (props) => {
    return (
            <div style={{height: '100%, overScrollY: 'scroll'}}>
                超出高度滚动:这里100%参照父容器:高阶方法提供的包裹父组件
            </div>
        );
}
export default customizeHeightWrap(ScrollComponent);
相关推荐
阿࿆杰࿆4 小时前
solon-flow基于bpmnJs的流程设计器
vue·流程图·react
许泽宇的技术分享1 天前
ReAct Agent:让AI像人类一样思考与行动的革命性框架
人工智能·agent·react
青衫客363 天前
用 Python 实现一个“小型 ReAct 智能体”:思维链 + 工具调用 + 环境交互
python·大模型·llm·react
柯北(jvxiao)10 天前
Vue vs React 多维度剖析: 哪一个更适合大型项目?
前端·vue·react
袋鼠云数栈前端10 天前
扣子 Coze 产品体验功能
大数据·ai·react
想你依然心痛15 天前
React 表单处理:移动端输入场景下的卡顿问题与防抖优化方案
react
亦世凡华、20 天前
React--》实现 PDF 文件的预览操作
经验分享·pdf·react·pdf预览
技术路上的探险家21 天前
Web3:在 VSCode 中使用 Vue 前端与已部署的 Solidity 智能合约进行交互
vscode·web3·区块链·交互·react·solidity·ethers.js
友莘居士1 个月前
Dify中的Agent和发现和调用mcp工具两个节点调用的异同
agent·react·dify·functioncalling·mcp
aiguangyuan1 个月前
前端开发性能优化概要
系统架构·vue·react·前端开发