在staless组件上添加defaultProps

时间:2018-02-28 16:40:02

标签: javascript reactjs

也许这是一个愚蠢的问题,但我不知道为什么我无法在像这样的无状态组件上添加基于另一个道具的默认值:

const Link = ({
  children,
  target,
  rel = target === '_blank' && 'noopener noreferrer',
  href,
  ...attributtes
}) => (
  <a
    {...attributtes}
    target={target}
    rel={rel}
    href={href}
  >
    {children}
  </a>
);

Link.defaultProps = {
  children: <div />,
  target: null,
  rel: null,
};

Link.propTypes = {
  children: PropTypes.node,
  href: PropTypes.string.isRequired,
  target: PropTypes.string,
  rel: PropTypes.string,
};

export default Link;

2 个答案:

答案 0 :(得分:2)

除非传递undefined,否则不使用默认参数值。这是一个简单的例子,说明这里发生了什么。

function test(a="foo", b="bar") {
  console.log(a, b);
}

test(undefined, null);
// prints "foo null"

target移除reldefaultProps,或将其设为undefined

Link.defaultProps = {
  children: <div />,
  target: undefined,
  rel: undefined,
};

答案 1 :(得分:0)

您可以尝试将target传递给返回默认值的函数:

const Link = ({
    children,
    target,
    rel = getRel(target),
    href,
    ...attributtes
}) => (
    <a
        {...attributtes}
        target={target}
        rel={rel}
        href={href}
    >
        {children}
    </a>
);

Link.defaultProps = {
    children: <div />,
    target: null,
    rel: null,
};

Link.propTypes = {
    children: PropTypes.node,
    href: PropTypes.string.isRequired,
    target: PropTypes.string,
    rel: PropTypes.string,
};

const getRel = target => target === '_blank' && 'noopener noreferrer';

export default Link;

未经测试,因此不确定target是否会正确传递,但我知道您可以将函数返回值用作默认参数值https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters