我已经在几个问题线程 here 和 here 中回答了这个问题,以了解有关复杂性和注意事项的更多背景信息,但这里是该方法的要点。
-
您需要将菜单的宽度设置为自动,以便它可以拉伸以适应其内容。
-
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;