React Allotment设置defaultSizes=[0,100]后左侧面板无法完全隐藏
解决React Allotment面板设置defaultSizes为[0,100]仍显示左侧面板的问题
你遇到的问题是因为Allotment组件的<Allotment.Pane>默认带有最小宽度限制(默认值为20px),即使通过defaultSizes将面板宽度设为0,也会被这个最小宽度限制住,导致左侧面板仍有显示。可以通过以下两种方式解决:
方法一:设置左侧面板的最小宽度为0
给左侧<Allotment.Pane>添加minSize={0}属性,取消最小宽度限制,这样当尺寸设为0时就能完全隐藏,同时保留拖拽调整面板宽度的能力:
import React from "react"; import { Allotment } from "allotment"; import "./styles.css"; import "allotment/dist/style.css"; export default function App() { return ( <div className="App"> <div style={{ background: "blue", minHeight: "42px" }}>Monitor</div> <div style={{ display: "flex", height: "100%", background: "darkblue" }}> <div style={{ border: "1px solid orange", width: "100px", height: "100%", background: "gray" }} > side content </div> <div style={{ width: "100%", height: "100%" }}> <div style={{ width: "100%", height: "100%", background: "red", border: "3px solid yellow" }} > <Allotment defaultSizes={[0, 100]}> {/* 添加minSize={0}取消最小宽度限制 */} <Allotment.Pane minSize={0}> <div style={{ height: "40px", background: "brown" }}></div> <div style={{ display: "flex", height: "100%", flexDirection: "column", justifyContent: "space-between" }} > <div> <img style={{ width: "100%", height: "auto" }} src={require("./the-mandalorian.jpg")} alt="cat" /> </div> <div style={{ height: "20px", background: "brown" }}></div> </div> </Allotment.Pane> <Allotment.Pane> <div style={{ height: "40px", background: "brown" }}></div> <div style={{ display: "flex", height: "100%", flexDirection: "column", justifyContent: "space-between" }} > <div> <img style={{ width: "100%", height: "auto" }} src={require("./nature.jpg")} alt="cat" /> </div> <div style={{ height: "20px", background: "brown" }}></div> </div> </Allotment.Pane> </Allotment> </div> </div> </div> </div> ); }
方法二:直接隐藏左侧面板
如果不需要左侧面板在初始状态下可拖拽显示,可以直接给左侧<Allotment.Pane>添加hidden={true}属性,组件会直接不渲染该面板,彻底隐藏:
// 仅修改Allotment内部的Pane部分 <Allotment defaultSizes={[0, 100]}> {/* 添加hidden={true}直接隐藏面板 */} <Allotment.Pane hidden={true}> <div style={{ height: "40px", background: "brown" }}></div> <div style={{ display: "flex", height: "100%", flexDirection: "column", justifyContent: "space-between" }} > <div> <img style={{ width: "100%", height: "auto" }} src={require("./the-mandalorian.jpg")} alt="cat" /> </div> <div style={{ height: "20px", background: "brown" }}></div> </div> </Allotment.Pane> <Allotment.Pane> {/* 右侧面板内容 */} </Allotment.Pane> </Allotment>
两种方法的区别
- 方法一保留了面板的拖拽调整能力,用户后续可以通过拖拽分隔条重新显示左侧面板;
- 方法二直接移除了面板的渲染,更彻底,适合不需要初始拖拽显示的场景。
内容的提问来源于stack exchange,提问作者walee
相关产品推荐
相关产品推荐

