首页 > 解决方案 > React:如何继承 PropTypes?

问题描述

我有一个 React Router Dom 和 Material UI 的包装器组件:

import Button from '@material-ui/core/Button';
import React from 'react';
import { Link as RouterLink } from 'react-router-dom';

const forwardedLink = React.forwardRef((props, ref) => (
  <RouterLink innerRef={ref} {...props} />
));

function Link(props) {
  return (
    <Button component={forwardedLink} {...props}>
      {props.children}
    </Button>
  );
}

Link.propTypes = // ?

export default Link;

我怎样才能给出LinkProp-Types from Button

标签: javascriptreactjsmaterial-uireact-router-domreact-proptypes

解决方案


请参阅this other SO answer,以下应该可以。

/**
 * @type React.ForwardRefRenderFunction<React.FunctionComponent, ButtonPropTypes>
 */
const Button = forwardRef(({ text, icon }, ref) => (
  <button ref={ref}>{text}{icon}</button>
))

const ButtonPropTypes = {
  text: string.isRequired,
  icon: string.isRequired,
}

Button.propTypes = ButtonPropTypes

推荐阅读