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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42463263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:25:50  来源:igfitidea点击:

Wrapping a react-router Link in an html button

htmlreactjsbuttonhyperlinkrouter

提问by Jose Rivera

Using suggested method: This is the result: A link in the button, Code in between comment lines

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

I was wondering if there is a way to wrap a Linkelement from 'react-router'in an HTML buttontag using react.

我想知道是否有办法使用 react将Link元素从'react-router'HTMLbutton标签中包装起来。

I currently have Linkcomponents to navigate pages in my app, but I would like to map that functionality to my HTML buttons.

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

enter image description hereenter image description here

在此处输入图片说明在此处输入图片说明

回答by Naren Yellavula

Do wrapping in the reverse way and you get the original button with the Link attached. No CSS changes required.

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

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

Here button is HTML button. It is also applicable to the components imported from third party libraries like Semantic-UI-React.

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

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

While this will render in a web browser, beware that:
??Nesting an html buttonin an html a(or vice-versa) is not valid html

虽然这将在 Web 浏览器中呈现,但请注意:
?? 在 htmlbutton中嵌套html a(反之亦然)不是有效的 html

回答by Beau Smith

LinkButtoncomponent - a solution for React Router v4

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

First, a note about many other answers to this question.

首先,关于这个问题的许多其他答案的说明。

?? Nesting <button>and <a>is not valid html. ??

?? 嵌套<button>并且<a>是无效的 html。??

Any answer here which suggests nesting a html buttonin a React Router Linkcomponent (or vice-versa) will render in a web browser, but it is not semantic, accessible, or valid html:

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

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

?Click to validate this markup with validator.w3.org?

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

This can lead to layout/styling issues as buttons are not typically placed inside links.

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



Using an html <button>tag with React Router <Link>component.

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

If you only want an html buttontag…

如果你只想要一个 htmlbutton标签......

<button>label text</button>

…then, here's the right way to get a button that works like React Router's Linkcomponent…

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

Use React Router's withRouterHOC to pass these props to your component:

使用 React Router 的withRouterHOC 将这些 props 传递给你的组件:

  • history
  • location
  • match
  • staticContext
  • history
  • location
  • match
  • staticContext


LinkButtoncomponent

LinkButton成分

Here's a LinkButtoncomponent for you to copy/pasta:

这是一个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)

Then import the component:

然后导入组件:

import LinkButton from '/components/LinkButton'

Use the component:

使用组件:

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

If you need an onClick method:

如果您需要一个 onClick 方法:

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

回答by Chase James

Why not just decorate link tag with the same css as a button.

为什么不使用与按钮相同的 css 来装饰链接标签。

<Link 
 className="btn btn-pink"
 role="button"
 to="/"
 onClick={this.handleClick()}
> 
 Button1
</Link>

回答by Inam Ul Huq

If you are using react-router-domand material-uiyou can use ...

如果您正在使用react-router-dom并且material-ui可以使用...

import { Link } from 'react-router-dom'
import Button from '@material-ui/core/Button';

<Button component={Link} to="/open-collective">
  Link
</Button>

You can read more here.

您可以在此处阅读更多内容。

回答by Alan

I use Router and < Button/>. No < Link/>

我使用路由器和 < Button/>。没有<链接/>

<Button onClick={()=> {this.props.history.replace('/mypage')}}>
   HERE
</Button>

回答by pflevy

For anyone looking for a solution using React 16.8+(hooks) and React Router 5:

对于使用React 16.8+(钩子)和 React Router 5寻找解决方案的任何人:

You can change the route using a button with the following code:

您可以使用带有以下代码的按钮更改路线:

<button onClick={() => props.history.push("path")}>

React Router providessome props to your components, including the push()function on historywhich works pretty much like the < Link to='path' > element.

React Router 为您的组件提供了一些道具,包括历史上push()函数,它的工作方式与 < Link to='path' > 元素非常相似。

You don't need to wrap your components with the Higher Order Component "withRouter" to get access to those props.

你不需要用高阶组件“withRouter”包装你的组件来访问这些道具。

回答by SandroMarques

You can use useHistoryhooksince react-router v5.1.0.

react-router v5.1.0以来,您可以使用useHistory钩子

The useHistoryhook gives you access to the history instance that you may use to navigate.

useHistory挂钩使您可以访问可用于导航的历史记录实例。

import React from 'react'
import { useHistory } from 'react-router'

export default function SomeComponent() {
  const { push } = useHistory()
  ...
  <button
    type="button"
    onClick={() => push('/some-link')}
  >
    Some link
  </button>
  ...
}

回答by Obed

With styled components this can be easily achieved

使用样式组件可以轻松实现

First Design a styled button

首先设计一个样式按钮

import styled from "styled-components";
import {Link} from "react-router-dom";

const Button = styled.button`
  background: white;
  color:red;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid red;
  border-radius: 3px;
`
render(
    <Button as={Link} to="/home"> Text Goes Here </Button>
);

check styled component's homefor more

检查样式组件的主页以获取更多信息

回答by Acts7Seven

Many of the solutions have focused on complicating things.

许多解决方案都专注于使事情复杂化。

Using withRouter is a really long solution for something as simple as a button that links to somewhere else in the App.

使用 withRouter 是一个非常长的解决方案,对于像链接到应用程序中其他地方的按钮这样简单的东西。

If you are going for S.P.A. (single page application), the easiest answer I have found is to use with the button's equivalent className.

如果您要使用 SPA(单页应用程序),我找到的最简单的答案是与按钮的等效类名一起使用。

This ensures you are maintaining shared state / context without reloading your entire app as is done with

这可确保您保持共享状态/上下文,而无需像之前那样重新加载整个应用程序

import { NavLink } from 'react-router-dom'; // 14.6K (gzipped: 5.2 K)

// Where link.{something} is the imported data
<NavLink className={`bx--btn bx--btn--primary ${link.className}`} to={link.href} activeClassName={'active'}>
    {link.label}
</NavLink>

// Simplified version:
<NavLink className={'bx--btn bx--btn--primary'} to={'/myLocalPath'}>
    Button without using withRouter
</NavLink>