我有一个组件,它呈现带有图标和文本的 Material UI MenuItem:
export default class ProjectMenuItem extends Component {
render() {
return (
<MenuItem onClick={this.props.onClick}>
<ListItemIcon>{this.props.iconComponent}</ListItemIcon>
<ListItemText primary={this.props.text} />
</MenuItem>
);
}
}
这工作正常。我正在努力理解的是为什么我会收到 警告:不能为函数组件提供引用。尝试访问此引用将失败。 如果我将此组件更改为功能组件:
export const ProjectMenuItem = ({ onClick, iconComponent, text }) => {
return (
<MenuItem onClick={onClick}>
<ListItemIcon>{iconComponent}</ListItemIcon>
<ListItemText primary={text} />
</MenuItem>
);
};
父组件: <StyledMenu
id='customized-menu'
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={handleClose}>
{projectMenuItens.map((menuItem, i) => (
<ProjectMenuItem
key={i}
onClick={menuItem.onClick}
text={menuItem.text}
iconComponent={menuItem.iconComponent}
/>
))}
</StyledMenu>
完整的警告是: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)
.
最佳答案
StyledMenu
组件尝试为您的 ProjectMenuItem
分配一个引用成分。 Refs 不能用于函数组件,因为它们没有实例。您只能在类组件或 DOM 元素上使用它们。
如果你想要 ProjectMenuItem
要成为功能组件,请使用 react 的 React.forwardRef
公用事业:
export const ProjectMenuItem = React.forwardRef(({onClick, iconComponent, text}, ref) => (
<MenuItem onClick={onClick} ref={ref}>
<ListItemIcon>{iconComponent}</ListItemIcon>
<ListItemText primary={text} />
</MenuItem>
));
您可以在 the official react docs 中阅读有关引用的更多信息.
关于reactjs - react 警告 : Function components cannot be given refs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62645556/