【问题标题】:How set react-select width depending on biggest option width?如何根据最大选项宽度设置反应选择宽度?
【发布时间】:2019-05-13 12:23:34
【问题描述】:

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

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

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

【问题讨论】:

  • 欢迎来到 StackOverflow,我建议您阅读此 guide for Minimal, Complete, and Verifiable example 并向我们展示您已经尝试解决问题的方法。
  • 我添加了最小示例。
  • 但是在你的例子中只有一个短输入和最长值的选项,你真正想要做什么?在“选定选项”中仅显示标签。
  • 我需要根据最长的选项自动控制大小。现在控件在父元素宽度上展开。

标签: css reactjs styles react-select


【解决方案1】:

我已经在几个问题线程 herehere 中回答了这个问题,以了解有关复杂性和注意事项的更多背景信息,但这里是该方法的要点。

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

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

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

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

结果可见here at this 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多