如何在 ReactJS 中将 Routerlink 放在 IconButton 中

How to Put Routerlink in IconButton in ReactJS

如何将路由器链接放入 reactjs 按钮?

我试过下面这两个:第一个改变颜色,第二个,我不喜欢它,因为它正在重新加载页面。

第一个

<Link to="/settings">
    <IconButton color="inherit">
        <SettingsIcon />
    </IconButton>
</Link>

第二个

<IconButton color="inherit" href="/settings">
    <SettingsIcon />
 </IconButton>
import React from "react";
import { useHistory } from "react-router-dom";

export default function Component() {
    const history = useHistory();

    return (
        <IconButton color="inherit" onClick={() => history.push("/setting")}>
            <SettingsIcon />
        </IconButton>
    );
}

@BeHappy 的解决方案很好,但是您可以使用组合来实现。无需使用钩子。

import React from 'react';
import { Link } from 'react-router-dom';
import { IconButton } from '@material-ui/core';
import SettingsIcon from '@material-ui/icons/Settings';

export default function Component() {
  return (
    <IconButton component={Link} to="/setting">
      <SettingsIcon />
    </IconButton>
  );
}

我能够将 Link 注入到 IconButton 中,如下所示。这种方法通过在包装 Link 组件的 span 中捕获它们来保留 material-ui 类 和 CSS 样式。同样的span也用来存放前向引用ref。我不确定为什么需要它,但将其遗漏似乎会产生警告。

import React from "react";
import { IconButton } from '@material-ui/core';
import SettingsIcon from '@material-ui/icons/Settings';

export default function Component() {
  return (
    <IconButton component={React.forwardRef(
      ({children, ...props}, ref) => (
        <span {...props} ref={ref}><Link>{children}</Link></span>
      )
    )}>
      <SettingsIcon />
    </IconButton>
  )
}