分配的可變道具的首選大小無法正常工作。
P粉349222772
P粉349222772 2024-03-30 09:42:29
0
1
339

我想為編輯器製作一個可拖曳的分割面板。其行為主要類似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學習者快速成長!