React MUI 自定义 Autocomplete 的 Popper 组件
React MUI customizing Autocomplete's Popper component
我想自定义 Autocomplete 组件自带的 Popper 的宽度。
在我的例子中,自动完成组件被放置在父组件内,旁边是一个 TextField。
这里是 Codesandbox 上的片段:
目前我有以下内容:
父组件背景颜色设置为绿色。
我的目标:Autocomplete Popper 组件应该覆盖整个绿色区域,换句话说,由父组件分隔的整个区域(因此也包括 TextField) .
编辑 1: 在 Amr Eraky 回答之后(解决宽度问题)
编辑 2:
因此,预期的行为如下(抱歉我的绘图技术不佳,我希望它无论如何都能被理解):
所以,我们这里有 2 个问题:
- 宽度
- 展示位置
至于宽度,我可以使用以下代码设置自定义宽度:
const PopperMy = useCallback((props) => {
return (<Popper {...props} style={{ width: 350 }} placement='right-end' />)
},
[]);
但是如您所见,这不是响应式的,甚至没有以某种方式绑定到父组件的宽度,因此这不是一个好的方法。
至于位置,我希望 popper overlap 它的父级,但是在 placement 选项中我找不到东西像这样,每个选项都不允许重叠。
您能否提出解决这些问题的方法?
你应该使用 Popper
的 anchorEl
属性来设置 popper 的位置。
anchorEl : Type of : HTML element | object | func
An HTML element, virtualElement, or a function that returns either. It's used to set the position of the popper. The return value will passed as the reference object of the Popper instance.
您可以使用 useRef
、
获得任何元素的 anchorEl
但是由于您的锚元素在其他组件中,您可以使用 id
并将 Popper
的高度设置为等于 anchorEl
的高度。
const PopperMy = React.useCallback((props) => {
const anchorEl = document.getElementById('new1'); // Or any other element
return <Popper {...props} anchorEl={anchorEl} style={{ width: anchorEl.clientWidth }} placement='bottom' />;
}, []);
我想自定义 Autocomplete 组件自带的 Popper 的宽度。 在我的例子中,自动完成组件被放置在父组件内,旁边是一个 TextField。
这里是 Codesandbox 上的片段:
目前我有以下内容:
父组件背景颜色设置为绿色。
我的目标:Autocomplete Popper 组件应该覆盖整个绿色区域,换句话说,由父组件分隔的整个区域(因此也包括 TextField) .
编辑 1: 在 Amr Eraky 回答之后(解决宽度问题)
编辑 2: 因此,预期的行为如下(抱歉我的绘图技术不佳,我希望它无论如何都能被理解):
所以,我们这里有 2 个问题:
- 宽度
- 展示位置
至于宽度,我可以使用以下代码设置自定义宽度:
const PopperMy = useCallback((props) => {
return (<Popper {...props} style={{ width: 350 }} placement='right-end' />)
},
[]);
但是如您所见,这不是响应式的,甚至没有以某种方式绑定到父组件的宽度,因此这不是一个好的方法。
至于位置,我希望 popper overlap 它的父级,但是在 placement 选项中我找不到东西像这样,每个选项都不允许重叠。
您能否提出解决这些问题的方法?
你应该使用 Popper
的 anchorEl
属性来设置 popper 的位置。
anchorEl : Type of : HTML element | object | func
An HTML element, virtualElement, or a function that returns either. It's used to set the position of the popper. The return value will passed as the reference object of the Popper instance.
您可以使用 useRef
、
获得任何元素的 anchorEl
但是由于您的锚元素在其他组件中,您可以使用 id
并将 Popper
的高度设置为等于 anchorEl
的高度。
const PopperMy = React.useCallback((props) => {
const anchorEl = document.getElementById('new1'); // Or any other element
return <Popper {...props} anchorEl={anchorEl} style={{ width: anchorEl.clientWidth }} placement='bottom' />;
}, []);