reactjs - 路由中的 withRouter 和 props 有什么作用?
问题描述
我对 React 很陌生,并试图了解我试图在项目中使用的组件的作用。
我之前使用过 react-router 中的 useHistory ,但这看起来很不一样。而且似乎正在使用道具。这里有没有人理解并可以解释这个组件的作用。withRouter 是做什么的,如果它与 useHistory 相同?
谢谢!
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)
解决方案
withRouter
是一个高阶组件 (HOC),用于将路由器道具 ( match
, location
, history
) 注入到包装的组件中, LinkButton
.
在引擎盖下,它用于将, ,RouterContext
填充到包装的组件中。match
location
history
function withRouter(Component) {
const C = props => {
const { wrappedComponentRef, ...remainingProps } = props;
return (
<RouterContext.Consumer>
{context => {
return (
<Component
{...remainingProps}
{...context} // pass context (match, location, history)
ref={wrappedComponentRef}
/>
);
}}
</RouterContext.Consumer>
);
};
}
WhileuseHistory
只是反应路由器中的一个自定义钩子,仅使用 功能组件中history
的信息。
推荐阅读
- angular - 尝试打印 HTML 的画布
- python - Pycharm importerror:无法导入名称'_backcompat_magic_number'
- reactjs - Gatsby/Hugo/MKDocs 用于 React SPA 中的降价文档,具有动态功能
- c# - 如何退出正在运行的控制台应用程序?
- php - 如何修复 Laravel 上的“未找到视图”
- android - 提高性能 adb 调用
- sql - 重新格式化访问日期 SQL 的问题
- javascript - 如何在html中定义表格的宽度和高度?
- javascript - 使用 jquery-validation 验证焦点输出的日期字段
- mapbox - mapbox gl填充挤出高度过渡不起作用