如何为可拖拽Allotment面板的子区域设置合适高度?
解决方案:让Allotment面板的内容区自适应剩余空间
你可以通过CSS Flex布局实现内容区高度自适应剩余空间,无需手动计算视口高度或主区域高度,这种方式简洁且能自动适配拖拽后的面板变化。
关键修改点:
- 给第二个
Allotment.Pane的内部容器设置垂直Flex布局,让标题栏和内容区垂直分配空间 - 标题栏保持固定高度(或自适应内容),内容区设置
flex: 1占据剩余空间,同时开启滚动
修改后的完整代码:
import React from "react"; import { Allotment } from "allotment"; import "allotment/dist/style.css"; import styles from "./App.module.css"; export default class App extends React.Component { constructor(props) { super(props); this.state = { toExpand: true }; this.myRef = React.createRef(); } handleChange = (sizes) => { if (sizes.length > 1) { if (sizes[1] < 31) { this.setState({ toExpand: true }); } else { this.setState({ toExpand: false }); } } }; render() { return ( <div> <div className={styles.container}> <Allotment vertical onChange={this.handleChange} ref={this.myRef}> <Allotment.Pane> <div style={{ backgroundColor: "yellow", height: "100%" }}> Main Area </div> </Allotment.Pane> <Allotment.Pane preferredSize="0%"> {/* 新增垂直Flex布局容器 */} <div style={{ display: "flex", flexDirection: "column", height: "100%" }}> <div onClick={() => { if (this.state.toExpand) { this.myRef.current.resize([50, 50]); } else { this.myRef.current.resize([10000, 0]); } }} style={{ backgroundColor: "blue", padding: "8px", height: "30px", boxSizing: "border-box" }} > Console Title {this.state.toExpand ? "ArrowUp" : "ArrowDown"} </div> <div style={{ backgroundColor: "green", flex: 1, // 自动填充标题栏外的剩余空间 overflow: "auto" // 内容超出时触发滚动 }} > Content1 <br /> Content2 <br /> Content3 <br /> Content4 <br /> Content5 <br /> Content6 <br /> Content7 <br /> Content8 <br /> Content9 <br /> Content10 <br /> </div> </div> </Allotment.Pane> </Allotment> </div> </div> ); } }
原理说明:
Allotment.Pane的高度是拖拽分配后的剩余视口高度,内部容器设置height: 100%继承该高度- Flex布局中
flex: 1会让内容区自动填充标题栏之外的所有剩余空间 - 拖拽主区域改变面板高度时,Flex布局会自动重新分配空间,内容区始终适配剩余高度
内容的提问来源于stack exchange,提问作者SoftTimur
相关产品推荐
相关产品推荐

