gpt4 book ai didi

css - 如何根据最大选项宽度设置 react 选择宽度?

转载 作者:行者123 更新时间:2023-12-03 17:31:16 31 4
gpt4 key购买 nike

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

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

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

最佳答案

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

  • 您需要将菜单的宽度设置为自动,以便它可以拉伸(stretch)以适应其内容。
  • onMount,设置菜单样式(高度:0,可见性:隐藏)并使用内部 ref 方法打开菜单
  • 使用 onMenuOpen 属性,使用等待 1ms 的函数,获取 listMenuRef 的宽度,然后关闭/重置 menuIsOpen。
  • 使用计算出的宽度,您现在可以设置 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;

    关于css - 如何根据最大选项宽度设置 react 选择宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53742315/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com