【问题标题】:React: How to inherit PropTypes?React:如何继承 PropTypes?
【发布时间】:2020-02-24 03:43:39
【问题描述】:

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

我怎样才能给Link 来自Button 的Prop-Types?

【问题讨论】:

  • Link.propTypes = Button.propTypes; ?
  • @zerkms 不幸的是,这不起作用。
  • “不起作用”到底是什么意思?
  • 表示组件没有得到propTypes ????
  • 查看这篇文章,如果您主要使用 propTypes 来进行智能感知,它可能会对您有所帮助,我只是偶然发现了它,特别是“技巧”部分和解释“通过添加 @augments {Component} 到您的组件的 JSDoc,您将向您的 Class 组件添加完整的 PropTypes 建议:" dev.to/maxbvrn/react-props-auto-complete-in-vs-code-2ana - 如果它不能解决问题,它可能会为您指明方向 =)

标签: javascript reactjs material-ui react-router-dom react-proptypes


【解决方案1】:

请参阅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

【讨论】:

    【解决方案2】:

    哎呀.. 抱歉,我一开始没有看到您正在尝试获取 来自节点模块的 propTypes。无论如何..如果有人需要这个 在自己的组件中继承 propTypes 我留下答案*

    这对我有用(使用我自己的组件) 将 props 导出为常量,并将其分配给继承对象和继承对象中的 component.propTypes。

    注意,首先我犯了一个我没有看到的错误。我忘了在所有内部对象上使用形状,如下所示:

    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 的人有所帮助??
    猜你喜欢
    • 2017-03-12
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    相关资源
    最近更新 更多