[英]React Warning: Function components cannot be given refs
I have a Component that renders a Material UI MenuItem with icon and text:我有一个使用图标和文本呈现 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>
);
}
}
This works fine.这工作正常。 What I am struggling to understand is why I get a Warning: Function components cannot be given refs.我很难理解的是为什么我会收到警告:Function 组件不能给出参考。 Attempts to access this ref will fail.尝试访问此 ref 将失败。 if I change this component to a functional component :如果我将此组件更改为功能组件:
export const ProjectMenuItem = ({ onClick, iconComponent, text }) => {
return (
<MenuItem onClick={onClick}>
<ListItemIcon>{iconComponent}</ListItemIcon>
<ListItemText primary={text} />
</MenuItem>
);
};
The parent component:父组件:
<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>
The full warning is:完整的警告是:
Warning: Function components cannot be given refs.警告:不能给 Function 组件提供参考。 Attempts to access this ref will fail.尝试访问此 ref 将失败。 Did you mean to use React.forwardRef()?你的意思是使用 React.forwardRef() 吗? Check the render method of
ForwardRef(Menu)
.检查ForwardRef(Menu)
的渲染方法。
The StyledMenu
component tries to assign a ref to your ProjectMenuItem
components. StyledMenu
组件尝试将 ref 分配给您的ProjectMenuItem
组件。 Refs cannot be used on function components because they don't have instances. Refs 不能用于 function 组件,因为它们没有实例。 You may only use them on class components or DOM elements.您只能在 class 组件或 DOM 元素上使用它们。
If you want ProjectMenuItem
to be a function component, use react's React.forwardRef
utility:如果您希望ProjectMenuItem
成为 function 组件,请使用 react 的React.forwardRef
实用程序:
export const ProjectMenuItem = React.forwardRef(({onClick, iconComponent, text}, ref) => (
<MenuItem onClick={onClick} ref={ref}>
<ListItemIcon>{iconComponent}</ListItemIcon>
<ListItemText primary={text} />
</MenuItem>
));
You can read more on refs in the official react docs .您可以在官方 react docs中阅读更多关于 refs 的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.