分配的可变道具的首选大小无法正常工作。
P粉349222772
P粉349222772 2024-03-30 09:42:29
0
1
341

我想为编辑器制作一个可拖动的分割面板。其行为主要类似于CodeSandbox的Console面板:

  1. 当我们点击Console时,面板展开,箭头变为ArrowDown用于关闭。
  2. 面板的边框是可拖动的。
  3. 当我们在展开的面板上点击 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 &nbsp;
                {this.state.toExpand ? "ArrowUp" : "ArrowDown"}
              </div>
            </Allotment.Pane>
          </Allotment>
        </div>
      </div>
    );
  }
}

P粉349222772
P粉349222772

全部回复(1)
P粉512526720

这不是问题,它确实发生了变化,但是,文档指出:

它没有配置为在 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);
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!