MUI v5 Autocomplete自定义ListboxComponent遇ref传递错误求助
解决MUI v5 Autocomplete中ListboxComponent的ref传递错误
错误原因
当你用匿名函数返回<ListBox>作为ListboxComponent时,MUI的Autocomplete会尝试给这个匿名组件传递ref,用于控制列表框的交互行为。但这个匿名组件没有通过forwardRef将ref转发给内部的ListBox组件(尽管ListBox本身已用forwardRef处理),导致React无法正确传递ref,从而抛出警告。
解决方案
方案一:手动在匿名函数中传递ref
从Autocomplete传入的props中解构出ref,单独传递给ListBox(因为ListBox是forwardRef组件,ref需要作为独立属性传递,而非包含在展开的props里):
<Autocomplete // 其他props... ListboxComponent={p => { const { ref, ...restProps } = p; return <ListBox ref={ref} {...restProps} test="test" />; }} />
方案二:创建带forwardRef的包装组件
如果需要复用这个带自定义props的列表组件,可以单独定义包装组件,用forwardRef处理ref传递:
import { forwardRef } from 'react'; import { ListBox } from './your-component-path'; const CustomListBox = forwardRef((props, ref) => { return <ListBox ref={ref} {...props} test="test" />; }); // 在Autocomplete中使用 <Autocomplete // 其他props... ListboxComponent={CustomListBox} />
为什么直接传ListBox没问题?
因为ListBox本身已经通过forwardRef正确处理了ref的接收与转发,Autocomplete传递的ref可以直接到达ListBox内部的目标元素,因此不会触发警告。
内容的提问来源于stack exchange,提问作者Hadji Andrei
相关产品推荐
相关产品推荐

