我想自定义自动完成组件附带的 Popper 的宽度。 在我的例子中,自动完成组件被放置在父组件内,旁边是一个文本字段。
这是 Codesandbox 上的代码片段:
父组件背景色设置为绿色。
我的目标:自动完成 Popper 组件应覆盖整个绿色区域,换句话说,由父组件界定的整个区域(因此也是 TextField)。
编辑2: 因此,预期行为如下(抱歉我糟糕的图形技能,无论如何我希望它是可以理解的):
所以,我们这里有两个问题:
- 宽度
- 展示位置
至于宽度,我可以使用以下代码设置自定义宽度:
const PopperMy = useCallback((props) => {
return (<Popper {...props} style={{ width: 350 }} placement='right-end' />)
},
[]);
但正如您所看到的,这不是响应式的,甚至没有以某种方式绑定(bind)到父组件的宽度,因此这不是一个好方法。
至于放置,我希望弹出器重叠其父级,但在放置选项中我找不到这样的东西,每个选项都不允许重叠。
您能否提出解决这些问题的方法?
最佳答案
您应该使用 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
,
但由于您的 anchor 元素位于其他组件中,您可以使用 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' />;
}, []);
关于reactjs - React MUI 自定义 Autocomplete 的 Popper 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72301310/