我正在使用Material-UI来设计一个React应用程序。我试图在<Menu>
组件中使用自己的自定义功能组件,但是出现了奇怪的错误:
Warning: Function components cannot be given refs.
Attempts to access this ref will fail.
Did you mean to use React.forwardRef()?
Check the render method of ForwardRef(Menu).
in TextDivider (at Filter.js:32)
出现这种情况的JSX看起来像这样:(第32行是TextDivider组件)
<Menu>
<TextDivider text="Filter Categories" />
<MenuItem>...</MenuItem>
</Menu>
TextDivider是什么:
const TextDivider = ({ text }) => {
const [width, setWidth] = useState(null);
const style = {
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center'
};
const hrStyle = {
width: `calc(100% - ${width}px)`,
marginRight: 0,
marginLeft: 0
};
const spanStyle = {
color: '#555',
whiteSpace: 'nowrap'
};
const ref = createRef();
useEffect(() => {
if (ref.current) {
const width = ref.current.getBoundingClientRect().width + 35;
console.log('width', width);
setWidth(width);
}
}, [ref.current]);
return (
<div style={style}>
<span ref={ref} style={spanStyle}>{ text }</span>
<Divider className="divider-w-text" style={ hrStyle }/>
</div>
);
};
奇怪的是,当在常规容器中单独设置此组件时,它可以完美地呈现,但似乎只有在<Menu>
组件内渲染时才会出现此错误。
此外,我发现如果将TextDivider包装在一个div中,这个错误就会完全消失:
<Menu>
<div>
<TextDivider text="Filter Categories" />
</div>
<MenuItem>...</MenuItem>
</Menu>
然而,对我来说,这感觉像是用胶带临时修补,我更想了解为什么我不能只在菜单中渲染此组件的根本问题。我在我的函数组件中没有使用任何Material-UI ref,在我的组件中也没有将ref放置在组件上,所以我不明白为什么会引发此错误。
非常感谢您能提供有关此行为发生原因的任何见解。
我尝试过使用useCallback hook、createRef()、useRef(),并阅读了我能找到的所有有关在函数组件中使用hook的内容。错误本身似乎是误导性的,因为即使是React官方文档也展示了在函数组件中使用refs的情况:https:// reactjs.org / docs / hooks-reference.html#useref