React:如何继承 PropTypes?

4
我有一个用于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;

我该如何将Button的Prop-Types赋给Link

Link.propTypes = Button.propTypes; 的翻译是:Link.propTypes = Button.propTypes; - zerkms
@zerkms 很遗憾,这不起作用。 - J. Hesters
“不起作用”具体指什么? - zerkms
这意味着该组件未获取到propTypes - J. Hesters
如果您主要使用propTypes来进行智能感知,请查看此帖子,它可能会对您有所帮助。我刚刚偶然发现了它,特别是“技巧”部分和“通过在组件的JSDoc中添加@augments {Component <Props,State>},您将为Class组件添加完整的PropTypes建议:”https://dev.to/maxbvrn/react-props-auto-complete-in-vs-code-2ana
  • 如果它不能解决问题,它可能会指引您一个方向 =)
- JimiSweden
2个回答

2
请参考这个Stack Overflow答案,下面的代码应该可以工作。
/**
 * @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

2
抱歉,起初我没有看到您正在尝试从node模块中获取propTypes。无论如何,如果有人需要在自己的组件中继承propTypes,则可以使用以下方法: 将props导出为常量,并将其分配给继承和被继承对象中的component.propTypes。
以下是我的示例代码(使用自己的组件):

请注意,首先我犯了一个错误,我忘记对所有内部对象使用shape,就像这样:

export const configurationPropTypes = {  
  id: PropTypes.string,
  // note: PropTypes.shape not wrapping the 'os' object
  os: {
      version: PropTypes.string,
      locale: PropTypes.string
  }
};


上面是错误的,下面是正确的。=)
//component being inherited 'ConfigurationListItem.js'
export const configurationPropTypes = {  
  id: PropTypes.string,
  os: PropTypes.shape({
      version: PropTypes.string,
      locale: PropTypes.string
  })
};

ConfigurationListItem.propTypes = configurationPropTypes;

//in 'QueueListItem.js', the component using ConfigurationListItem and inheriting it's propTypes

import ConfigurationListItem , {configurationPropTypes}from './ConfigurationListItem';
//...
QueueListItem.propTypes = {
  id: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
  configurations: PropTypes.arrayOf(PropTypes.shape(configurationPropTypes))
}


嗨,感谢您的回答。是的,您说得对,我想知道如何从本地标签继承。这个答案对于那些想要继承自定义Prop-Types的人仍然可能有帮助。 - J. Hesters

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接