如何根据最大选项宽度设置反应选择宽度?

Yar*_*khp 5 css styles reactjs react-select

如何根据最大选项宽度设置反应选择输入宽度?选项位置是绝对的,因此它们的大小不会影响父 div 的宽度。

例如:https : //codesandbox.io/s/9o4rkklz14

我需要选择宽度是最长的选项宽度。

Bor*_*ady -1

我已经在此处此处的几个问题线程中回答了这个问题,以获取有关复杂性和警告的更多背景信息,但这是该方法的要点。

  1. 您需要将菜单的宽度设置为自动,以便它能够拉伸以适合其内容。

  2. onMount,设置菜单样式(高度:0,可见性:隐藏)并使用内部 ref 方法打开菜单

  3. 通过 onMenuOpen 属性,使用等待 1 毫秒的函数,获取 listMenuRef 的宽度,然后关闭/重置 menuIsOpen。

  4. 通过计算出的宽度,您现在可以设置 ValueContainer 的宽度。

结果可以在这个codesandbox中看到

下面发布了代码...

import React, { useState, useRef, useEffect } from "react";
import Select from "react-select";

const App = (props) => {
  const selectRef = useRef();

  const [menuIsOpen, setMenuIsOpen] = useState();
  const [menuWidth, setMenuWidth] = useState();
  const [isCalculatingWidth, setIsCalculatingWidth] = useState(false);

  useEffect(() => {
    if (!menuWidth && !isCalculatingWidth) {
      setTimeout(() => {
        setIsCalculatingWidth(true);
        // setIsOpen doesn't trigger onOpenMenu, so calling internal method
        selectRef.current.select.openMenu("first");
        setMenuIsOpen(true);
      }, 1);
    }
  }, [menuWidth, isCalculatingWidth]);

  const onMenuOpen = () => {
    if (!menuWidth && isCalculatingWidth) {
      setTimeout(() => {
        const width = selectRef.current.select.menuListRef.getBoundingClientRect()
          .width;
        setMenuWidth(width);
        setIsCalculatingWidth(false);

        // setting isMenuOpen to undefined and closing menu
        selectRef.current.select.onMenuClose();
        setMenuIsOpen(undefined);
      }, 1);
    }
  };

  const styles = {
    menu: (css) => ({
      ...css,
      width: "auto",
      ...(isCalculatingWidth && { height: 0, visibility: "hidden" })
    }),
    control: (css) => ({ ...css, display: "inline-flex " }),
    valueContainer: (css) => ({
      ...css,
      ...(menuWidth && { width: menuWidth })
    })
  };

  const options = [
    { label: "Option 1", value: 1 },
    { label: "Option 2", value: 2 },
    { label: "Option 3 is a reallly realllly long boi", value: 3 }
  ];

  return (
    <div>
      <div> Width of menu is {menuWidth}</div>
      <Select
        ref={selectRef}
        onMenuOpen={onMenuOpen}
        options={options}
        styles={styles}
        menuIsOpen={menuIsOpen}
      />
    </div>
  );
};

export default App;
Run Code Online (Sandbox Code Playgroud)