我做了一個https://github.com/johnwalley/allotment.的可拖動分割面板
我想意識到幾件事:
點擊展開或折疊分配B將展開或折疊分配B 我們可以拖動拆分器,拆分器的位置會在折疊分配區B之前保存,這樣我們可以在展開分配區B時返回到該位置。 當我們第一次擴展分配B時,我希望分配B的高度是整個高度的1/5。 我寫的代碼如下(https://codesandbox.io/s/reset-forked-f2f386?file=/src/App.js)。我無法同時意識到2)和3)。
有人知道為什么會這樣嗎?
import React from "react";
import { Allotment } from "allotment";
import "allotment/dist/style.css";
import "./style.css";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
toExpand: true,
lastExpandedSize: [200, 50]
};
this.myRef = React.createRef();
}
handleChangeAllotment = (sizes) => {
if (sizes.length > 1) {
if (sizes[1] < 31) {
this.setState({ toExpand: true });
} else {
this.setState({
toExpand: false,
lastExpandedSize: sizes // removing this line will set the initial sizes correctly, but will not be able to save last sizes.
});
}
}
};
undertakeExpandOrCollapse = () => {
if (this.state.toExpand) {
this.myRef.current.resize(this.state.lastExpandedSize);
} else {
this.myRef.current.resize([10000, 0]);
}
};
render() {
return (
<div
style={{
minWidth: 200,
height: "100vh",
overflowX: "auto",
width: "auto",
margin: "0px 0px 0px 0px"
}}
>
<Allotment
vertical
onChange={this.handleChangeAllotment}
ref={this.myRef}
>
<Allotment.Pane>
<span onClick={this.undertakeExpandOrCollapse}>
Expand or collapse the allotment B
</span>
</Allotment.Pane>
<Allotment.Pane preferredSize="0%" minSize={30}>
the allotment B
</Allotment.Pane>
</Allotment>
</div>
);
}
}
我的快速想法是,默認情況下,沒有保存的值,lastExpandedSize的值為null。感覺到這一點,我們傳遞五分之一的屏幕高度作為保存的高度。當關閉時,已經有一個保存的值,因此useState函數將從那時起返回該值。
// ...
constructor(props) {
super(props);
this.state = {
toExpand: true,
lastExpandedSize: null // set null to default
};
this.containerRef = React.createRef();
this.myRef = React.createRef();
}
/**
* Check to has LastExpandedSize
* @return {bool}
*/
hasLastExpandedSize = () => {
return this.state.lastExpandedSize !== null;
}
/**
* Get DefaultExpandedSize
* @param {number} ratio
* @param {number} height
* @return {number[]}
*/
getDefaultExpandedSize = (ratio = 5, height = 0) => {
if (height < 1) {
height = this.containerRef.current.clientHeight;
}
return [
height * (ratio - 1) / ratio,
height / ratio
];
}
handleChangeAllotment = (sizes) => {
if (sizes.length > 1) {
if (sizes[1] < 31) {
this.setState({ toExpand: true });
}
else {
this.setState({
toExpand: false,
lastExpandedSize: this.hasLastExpandedSize()
? sizes
: this.getDefaultExpandedSize()
});
}
}
};
// ...
<div
ref={this.containerRef}
style={{
minWidth: 200,
height: "100vh",
overflowX: "auto",
width: "auto",
margin: "0px 0px 0px 0px"
}}
>
...
</div>