首页 > 解决方案 > 导出部分 prop-types 以在组件的 props 中重用

问题描述

下面的代码片段演示了两种道具类型,我想将它们提取到单独的共享文件中以在其他组件中重用。

./Mycomponent.js

MyComponent.propTypes = {
  title: PropTypes.string,
  description: PropTypes.string,
  image: PropTypes.string,
}

MyComponent.defaultProps = {
  title: 'some default title',
  description: 'some default description',
  image: './image.jpg'
}

我想做一个通用的共享道具变量,只包含标题和描述。为了做到这一点,我创建了一个共享道具文件并将我想重复使用的道具提取到该文件中,如以下示例所示。

./shared-props.js

const fooProps = {
  title: PropTypes.string,
  description: PropTypes.string,
}

现在我想在./Mycomponent.js中重新使用它:

import { fooProps } from './shared-props.js';

MyComponent.propTypes = {
  ...fooProps, // <- re-use here
  image: PropTypes.string,
}; 

MyComponent.defaultProps = {
  title: 'some default title',
  // defaultProp "title" has no corresponding propTypes declaration.eslintreact/default-props-match-prop-types
  description: 'some default description',
  // defaultProp "description" has no corresponding propTypes declaration.eslintreact/default-props-match-prop-types
  image: './image.jpg'
}

const MyComponent = ({
  title, // "title" is missing in props validation [eslintreact/prop-types]
  description, // "description" is missing in props validation [eslintreact/prop-types]
  image,
}) => {
// ...

现在页面渲染得很好。这只是 ESLint 抛出这个错误吗?或者我应该以不同的方式导出道具?


更新:它在使用时确实有效,如下所示:

./shared-props.js

const fooProps = PropTypes.shape({
  title: PropTypes.string,
  description: PropTypes.string,
});

./Mycomponent.js:

import { fooProps } from './shared-props.js';

MyComponent.propTypes = {
  foo: fooProps, // <- only works when adding 'foo'
  image: PropTypes.string,
}; 

但后来我不得不添加另一个级别..

标签: reactjseslintreact-props

解决方案


推荐阅读