将 react-router 链接包装在 html 按钮中

新手上路,请多包涵

使用建议的方法: 结果如下:按钮中的链接注释行之间的代码

我想知道是否有办法使用 react 将 'react-router' 中的 Link 元素包装在 HTML button 标签中。

我目前有 Link 组件来导航我的应用程序中的页面,但我想将该功能映射到我的 HTML 按钮。

在此处输入图像描述在此处输入图像描述

原文由 Jose Rivera 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

虽然这将在 Web 浏览器中呈现,但请注意:

⚠️ 在 html 中嵌套 button a (反之亦然) 是无效的 html ⚠️。如果您想将 html 语义保留给屏幕阅读器,请使用另一种方法。

以相反的方式进行包装,您将获得带有链接的原始按钮。无需更改 CSS。

  <Link to="/dashboard">
     <button type="button">
          Click Me!
     </button>
 </Link>

这里的按钮是 HTML 按钮。它也适用于从 Semantic-UI-React 等第三方库导入的组件。

  import { Button } from 'semantic-ui-react'
 ...
 <Link to="/dashboard">
     <Button style={myStyle}>
        <p>Click Me!</p>
     </Button>
 </Link>

原文由 Naren Yellavula 发布,翻译遵循 CC BY-SA 4.0 许可协议

LinkButton 组件 - React Router v4 的解决方案

首先,注意这个问题的许多其他答案。

⚠️ 嵌套 <button><a> 是无效的 html。 ⚠️

任何建议在 React Router 中嵌套 html button 的答案 Link 组件(或反之亦然)将在网络浏览器中呈现,但它不是语义的、可访问的或有效的HTML:

 <a stuff-here><button>label text</button></a>
<button><a stuff-here>label text</a></button>

单击以使用 validator.w3.org 验证此标记

这可能会导致布局/样式问题,因为按钮通常不会放置在链接内。


使用 html <button> 标签和 React Router <Link> 组件。

如果你只想要一个 html button 标签……

 <button>label text</button>

…那么,这里是获得一个按钮的正确方法,它像 React Router 的 Link 组件一样工作……

使用 React Router 的 withRouter HOC 将这些道具传递给您的组件:

  • history
  • location
  • match
  • staticContext

LinkButton 组件

这是一个 LinkButton 组件供您复制/ _意大利面_:

 // file: /components/LinkButton.jsx
import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router'

const LinkButton = (props) => {
  const {
    history,
    location,
    match,
    staticContext,
    to,
    onClick,
    // ⬆ filtering out props that `button` doesn’t know what to do with.
    ...rest
  } = props
  return (
    <button
      {...rest} // `children` is just another prop!
      onClick={(event) => {
        onClick && onClick(event)
        history.push(to)
      }}
    />
  )
}

LinkButton.propTypes = {
  to: PropTypes.string.isRequired,
  children: PropTypes.node.isRequired
}

export default withRouter(LinkButton)

然后导入组件:

 import LinkButton from '/components/LinkButton'

使用组件:

 <LinkButton to='/path/to/page'>Push My Buttons!</LinkButton>

如果你需要一个 onClick 方法:

 <LinkButton
  to='/path/to/page'
  onClick={(event) => {
    console.log('custom event here!', event)
  }}
>Push My Buttons!</LinkButton>

更新: 如果您正在寻找在编写上述内容后可用的另一个有趣选项,请查看此 useRouter 挂钩

原文由 Beau Smith 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题