簡體   English   中英

React:如何繼承 PropTypes?

[英]React: How to inherit 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;

我怎樣才能給Link Prop-Types from Button

OOPS .. 抱歉,起初我沒有看到您正在嘗試從節點模塊獲取 propTypes。 無論如何..如果有人需要這個來在自己的組件中繼承propTypes,我會留下答案*

這對我有用(使用我自己的組件)將道具導出為常量並將其分配給繼承對象和繼承對象中的 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))
}

請參閱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