首页  >  问答  >  正文

分配的可变道具的首选大小无法正常工作。

我想为编辑器制作一个可拖动的分割面板。其行为主要类似于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粉349222772P粉349222772186 天前346

全部回复(1)我来回复

  • P粉512526720

    P粉5125267202024-03-31 00:18:13

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

    它没有配置为在 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);
    }

    回复
    0
  • 取消回复