You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用React+styled-components实现组件高度自适应剩余空间问题求解

问题原因

你原来的实现方式存在两个核心问题:

  • 组件首次渲染时,useRef绑定的DOM节点还未生成,input?.current?.style?.height 取值为空,且后续WritePanel高度变化时,ref值更新不会触发组件重渲染,BottomPanel高度无法同步更新
  • 手动计算高度的方案需要额外监听DOM高度变化,维护成本高,容错率低

解决方案

直接使用Flex弹性布局实现即可,不需要手动计算高度,完全匹配需求,适配性更强:
首先确认根节点高度已设置(否则百分比高度不生效):

html, body, #root {
  height: 100%;
  margin: 0;
  padding: 0;
}

完整组件代码:

import { useRef } from 'react';
import styled from 'styled-components';

const Wrapper = styled.div`
  height: 100%;
  display: flex;
  flex-direction: column;
`;

const TopBar = styled.div`
  height: 70px;
  flex-shrink: 0; /* 禁止被压缩 */
  background: red;
`;

const BottomPanel = styled.div`
  flex: 1; /* 自动占据剩余高度 */
  overflow: auto; /* 内容超出时可滚动,不会挤压其他元素 */
  background: blue;
`;

const WritePanel = styled.div`
  min-height: 50px;
  max-height: 150px;
  flex-shrink: 0; /* 禁止被压缩 */
  background: green;
  overflow-y: auto; /* 内容超出最大高度时滚动 */
`;

export default function Page() {
  const input = useRef(null);
  return (
    <Wrapper>
      <TopBar />
      <BottomPanel />
      <WritePanel ref={input} />
    </Wrapper>
  );
}

该方案会自动适配WritePanel的高度变化,不管它高度在50px~150px区间怎么调整,BottomPanel都会自动填充剩余空间。


内容的提问来源于stack exchange,提问作者some nooby questions

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 08:27:02