【发布时间】:2019-10-11 22:10:01
【问题描述】:
我正在使用 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 引用,也没有在 <TextDivider> 组件中的 <Divider> 组件上放置引用,所以我不明白它为什么会抛出这个错误。
如果您能深入了解为什么会发生这种行为,我们将不胜感激。
我尝试过使用 useCallback 钩子、createRef()、useRef(),并阅读了关于在功能组件中使用钩子的所有内容。该错误本身似乎具有误导性,因为即使反应文档本身也显示使用功能组件在这里引用:https://reactjs.org/docs/hooks-reference.html#useref
【问题讨论】:
-
它告诉你问题是什么...这里是文档:reactjs.org/docs/forwarding-refs.html
标签: reactjs material-ui react-hooks