首页 > 解决方案 > 路由中的 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)

标签: reactjsreact-router

解决方案


withRouter是一个高阶组件 (HOC),用于将路由器道具 ( match, location, history) 注入到包装的组件中, LinkButton.

在引擎盖下,它用于将, ,RouterContext填充到包装的组件中。matchlocationhistory

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的信息。


推荐阅读