簡體   English   中英

react-select 下拉菜單在模態中打開

[英]react-select dropdown opens inside modal

我有一個自定義模式,其中有 2 個 react-select 組件。 如果內容超過其大小,模態主體已准備好自動滾動,但反應選擇組件下拉列表在模態內部打開並出現此溢出,這是我不想要的。 沒有溢出,它工作正常。

我正在使用 CSS 模塊。

<div className={styles.modalBody}>
    {this.props.children}
</div>

.modalBody {
    padding: padding;
    flex: 1 1 auto;
    height: 45vh;
    max-height: 100%;
    overflow: auto;
}

<Select
    id={this.props.id}
    className={styles[this.props.selectType ? this.props.selectType : 'selectWhite']}
    classNamePrefix="select"
    name={this.props.name}
    value={selectedOption ? selectedOption : this.props.value}
    placeholder={this.props.placeholder}
    onChange={this.onChange}
    options={this.props.options}
    isDisabled={this.props.disabled}
    isSearchable={false}/>

我怎樣才能解決這個問題? 謝謝: :)

你想看看menuPortalTarget道具。 高級文檔中有一個主題 ,特別是提供了一個模態示例。 就像是:

  <Select
    {...otherProps}
    menuPortalTarget={document.body} />

如何在模態中顯示 select 菜單的完整示例(我在重要行添加了注釋,並在下面逐步說明):

import React, { useRef } from 'react';
import Select from 'react-select';
import { Dialog } from '@mui/material';

const MyModal: React.FC = () => {
    const ref = useRef<HTMLDivElement>(null);

    return (
        <Dialog
            // ...
            ref={ref} // stores a ref to the DOM node of the modal component
        >
            <Select
                // ...
                menuPortalTarget={ref.current} // pass the ref to `Select` to portal the select menu to the given DOM node
                styles={{
                    menuPortal: defaultStyles => ({  
                        ...defaultStyles,
                        paddingBottom: '10px', // style the menu when it's portalled into the DOM node given to `menuPortalTarget`
                    }),
                }}
            />
        </Dialog>
    );
};

export default MyModal;

分步說明

  1. 我用React.useRef鈎子創建了一個ref
  2. 我通過ref={ref}獲得了Dialog組件的引用(在此示例中是MUI 對話框組件(但可以是任何其他 Modal 組件)
  3. 我通過menuPortalTarget={ref.current}將該ref傳遞給react-selectSelect組件。
  4. 我必須通過paddingBottom: '10px',因為在我的情況下菜單看起來有點太高了。 您可能需要進行不同的調整。

進一步評論

  • document.body並沒有為我解決問題。 在這種情況下,菜單出現在我的模態后面。
  • 不幸的是, react-select門戶文檔不包含任何示例代碼,所以我希望這個示例對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM