【问题标题】:What does withRouter and props in routes?路由中的 withRouter 和 props 有什么作用?
【发布时间】:2020-02-24 09:34:10
【问题描述】:

我对 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)

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    withRouter 是一个Higher Order Component (HOC),用于将路由器道具(matchlocationhistory)注入到包装的组件LinkButton

    在底层它使用RouterContextmatchlocationhistory 填充到包装的组件中。

    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>
        );
      };
    }
    

    虽然useHistory 只是 React 路由器中的 custom hook,但在 function 组件中使用 only history 信息。

    【讨论】:

      猜你喜欢
      • 2020-01-10
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      • 2019-09-24
      • 1970-01-01
      相关资源
      最近更新 更多