简体   繁体   English

React:如何继承 PropTypes?

[英]React: How to inherit PropTypes?

I have a wrapper component for React Router Dom and Material UI:我有一个 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;

How can I give Link the Prop-Types from Button ?我怎样才能给Link Prop-Types from Button

OOPS.. sorry, I didn't see at first you are trying to get the propTypes from node-module. OOPS .. 抱歉,起初我没有看到您正在尝试从节点模块获取 propTypes。 anyhow.. if anyone needs this for inheriting propTypes in own components I leave the answer*无论如何..如果有人需要这个来在自己的组件中继承propTypes,我会留下答案*

This works for me (using my own components) Export the props as a constant and assign it to the component.propTypes in the inherited and in the inheriting objects.这对我有用(使用我自己的组件)将道具导出为常量并将其分配给继承对象和继承对象中的 component.propTypes。

Note, first I made a mistake that I didn't see.请注意,首先我犯了一个我没有看到的错误。 I had forgot to use shape on all the inner objects, like this:我忘记在所有内部对象上使用形状,如下所示:

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

Above is wrong, below is correct.上面是错误的,下面是正确的。 =) =)

//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))
}

See this other SO answer , the below should work.请参阅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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM