我想为编辑器制作一个可拖动的分割面板。其行为主要类似于CodeSandbox的Console面板:
Console时,面板展开,箭头变为ArrowDown用于关闭。Console 时,面板关闭,箭头变为 ArrowUp 进行展开。我有以下代码(https://codesandbox.io/s/reset-forked-ydhy97?file=/src/App.js:0-927),作者:https://github.com/johnwalley/allotment 。问题是 preferredSize 属性在 this.state.toExpand 之后没有更改。
有人知道为什么这不起作用吗?
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
};
}
render() {
return (
<div>
<div className={styles.container}>
<Allotment vertical>
<Allotment.Pane>Main Area</Allotment.Pane>
<Allotment.Pane preferredSize={this.state.toExpand ? "0%" : "50%"}>
<div
onClick={() => {
this.setState({ toExpand: !this.state.toExpand });
}}
>
Console
{this.state.toExpand ? "ArrowUp" : "ArrowDown"}
</div>
</Allotment.Pane>
</Allotment>
</div>
</div>
);
}
} Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这不是问题,它确实发生了变化,但是,文档指出:
它没有配置为在 prop 更改时更新,但是,如果将其设置为 ArrowDown 后双击边框,它将重置为 50%。
相反,如果您通过首先在构造函数中初始化引用来添加对 Allotment 元素的引用:
constructor(props) { super(props); this.allotment = React.createRef(); this.state = { toExpand: true }; }并将其指定为道具:
然后,您可以向 setState 添加回调,以便在更改调用重置函数的展开选项时:
resetAllotment() { if (this.allotment.current) { this.allotment.current.reset(); } } // ... this.setState({ toExpand: !this.state.toExpand }, () => this.resetAllotment());旁注,在 setState 回调中调用重置之前,分配组件似乎没有时间处理新的道具更改...但这对我来说不合逻辑,但是,您可以通过 hacky setTimeout 为 0ms 来解决此问题:
resetAllotment() { setTimeout(() => this.allotment.current && this.allotment.current.reset(), 0); }