使用 Tag 在 NavLink reactstrap 组件中传递属性

Using Tag to pass a attribute inside NavLink reactstrap component

谁能帮我弄清楚在 NavLink 组件中传递 Link 标签的意义是什么:

<NavLink tag={Link} to="/components/" activeClassName="active">Components</NavLink>

NavLink(reactstrap 组件)的代码如下:

import PropTypes from 'prop-types';
import classNames from 'classnames';
import { mapToCssModules, tagPropType } from './utils';

const propTypes = {
  tag: tagPropType,
  innerRef: PropTypes.oneOfType([PropTypes.object, PropTypes.func, PropTypes.string]),
  disabled: PropTypes.bool,
  active: PropTypes.bool,
  className: PropTypes.string,
  cssModule: PropTypes.object,
  onClick: PropTypes.func,
  href: PropTypes.any,
};

const defaultProps = {
  tag: 'a',
};

class NavLink extends React.Component {
  constructor(props) {
    super(props);

    this.onClick = this.onClick.bind(this);
  }

  onClick(e) {
    if (this.props.disabled) {
      e.preventDefault();
      return;
    }

    if (this.props.href === '#') {
      e.preventDefault();
    }

    if (this.props.onClick) {
      this.props.onClick(e);
    }
  }

  render() {
    let {
      className,
      cssModule,
      active,
      tag: Tag,
      innerRef,
      ...attributes
    } = this.props;

    const classes = mapToCssModules(classNames(
      className,
      'nav-link',
      {
        disabled: attributes.disabled,
        active: active
      }
    ), cssModule);

    return (
      <Tag {...attributes} ref={innerRef} onClick={this.onClick} className={classes} />
    );
  }
}

NavLink.propTypes = propTypes;
NavLink.defaultProps = defaultProps;

export default NavLink;

在这里你可以看到 NavLink returns 一个组件包裹在我们作为道具传递的标签中。 Link(react-router 组件)的基本功能即路由组件在这里没有完成。所以将它作为 NavLink 的道具传递让我感到困惑。

我相信这是他们如何在来自 react-router 或您想要使用的任何其他 Link 组件的 Link 组件上提供可重用性!我们基本上拥有的是:

// react-router/Link
<Link to="/about">About</Link>

他们在NavLink中有什么:

      <Tag {...attributes} ref={innerRef} onClick={this.onClick} className={classes} />

其中 {...attributes} 将是除以下以外的任何其他 属性: className, cssModule, active, tag, innerRef,因为它们是从 props 中销毁的。

所以,他们这样做的原因。

  1. 他们 needed/provided onClick 属性 Link 组件。
  2. 他们有自己的样式标准 className={classes}

并且,React 中最重要的事情之一是组件的可重用性,意思是,DRY 原则适用于此事,因为,假设您没有 NavLink 组件,而您想要在需要时为 Link 组件添加一个 onClick 道具,然后你就必须随身携带它:

  onClick(e) {
    if (this.props.disabled) {
      e.preventDefault();
      return;
    }

    if (this.props.href === '#') {
      e.preventDefault();
    }

    if (this.props.onClick) {
      this.props.onClick(e);
    }
  }

缩短:都是为了 DRY 原则