反应:如何继承PropTypes?

问题描述 投票:0回答:1

我有一个用于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的道具类型?

javascript reactjs material-ui react-router-dom react-proptypes
1个回答
0
投票

哎呀..抱歉,起初我没有看到您正在尝试获取来自节点模块的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))
}

© www.soinside.com 2019 - 2024. All rights reserved.