LinkButton 组件 - React Router v4 的解决方案
首先,关于这个问题的许多其他答案的注释。
⚠️ 嵌套 <button> 和 <a> 不是有效的 html。 ⚠️
此处任何建议在 React Router Link 组件中嵌套 html button(或反之亦然)的答案都将在 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☝
这可能会导致布局/样式问题,因为按钮通常不会放置在链接内。
使用带有 React Router <Link> 组件的 html <button> 标签。
如果你只想要一个 html button 标签……
<button>label text</button>
...那么,这里是获得像 React Router 的 Link 组件一样工作的按钮的正确方法...
使用 React Router 的 withRouter HOC 将这些 props 传递给您的组件:
history
location
match
staticContext
LinkButton组件
这里有一个LinkButton 组件供你复制/pasta:
// 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 hook。