【问题标题】:React Warning: Function components cannot be given refsReact 警告:不能给函数组件提供 refs
【发布时间】:2020-10-20 01:19:03
【问题描述】:

我有一个用图标和文本呈现 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>
    );
  }
}

这很好用。 我很难理解的是为什么我会收到 警告:函数组件不能被赋予 refs。尝试访问此 ref 将失败。 如果我将此组件更改为功能组件

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>

完整的警告是:

警告:函数组件不能被赋予 refs。尝试访问 这个裁判会失败。你的意思是使用 React.forwardRef() 吗?检查ForwardRef(Menu)的渲染方法。

【问题讨论】:

标签: reactjs material-ui


【解决方案1】:

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 中阅读更多关于参考的信息。

【讨论】:

  • 如果一切都按预期工作,忽略此错误会导致问题吗? (可能相关:react-router, forwardRef API in withRouter
  • @kca 上面的消息说的是“警告”而不是“错误”,并且是由 React 自己生成的,所以关于 React,如果你忽略这个警告,你不会得到任何运行时错误。但是,将受影响的功能组件用作子组件的其他组件可能依赖它接受 ref,因此请务必阅读文档并检查源代码。
猜你喜欢
  • 2021-06-05
  • 1970-01-01
  • 1970-01-01
  • 2020-08-10
  • 2021-05-26
  • 1970-01-01
  • 2020-02-22
  • 2019-11-27
  • 2019-03-28
相关资源
最近更新 更多