简体   繁体   English

如何在 React PropTypes 中使用导入值?

[英]How to use imported values in React PropTypes?

I'm creating PropTypes for a functional component and I want to use PropTypes.oneOf with an object imported from another file:我正在为功能组件创建PropTypes ,我想将PropTypes.oneOf与从另一个文件导入的 object 一起使用:

import { MODES } from '../../../Users';
(...)
ManageUserForm.propTypes = {
    mode: PropTypes.oneOf(Object.values(MODES)),
}

In Users.js , MODES looks like this:Users.js中, MODES看起来像这样:

export const MODES = {
    add: 'add', edit: 'edit', changePassword: 'changePassword',
    block: 'block', unblock: 'unblock', delete: 'delete'
};

But I get an error stating that MODES is undefined .但是我收到一条错误消息,指出MODES undefined For now, I solved it by just hardcoding the values, but that's inelegant and I want to improve it.现在,我只是通过对值进行硬编码来解决它,但这并不优雅,我想改进它。 What can I do?我能做什么?

EDIT: I recreated the problem in a sandbox: codesandbox.io编辑:我在沙箱中重新创建了问题: codesandbox.io

This would work but I will recommend to keep it in the same file because it was not imported when it defines the proptypes.这可行,但我建议将其保存在同一个文件中,因为它在定义 proptypes 时未被导入。

ManageUserForm.propTypes = {
  mode: PropTypes.oneOf(Object.values(require('../../../Users'))),
}

Here is a codeSandbox example https://codesandbox.io/s/react-example-forked-y1br4?file=/index.js这是一个 codeSandbox 示例https://codesandbox.io/s/react-example-forked-y1br4?file=/index.js

You have a circular dependency .你有一个循环依赖

  1. First the code imports Users.js from App.js .首先,代码从App.js Users.js
  2. Then Users.js imports UserCreator.js .然后Users.js导入UserCreator.js
  3. Then UserCreator.js imports ManageUserForm.js .然后UserCreator.js导入ManageUserForm.js
  4. Then ManageUserForm.js imports Users.js again然后Users.js再次导入ManageUserForm.js

All this even before MODES variable is being defined.所有这一切甚至在定义MODES变量之前。 You should not import Users.js in ManageUserForm.js since Users.js itself depends on ManageUserForm.js through UserCreator.js .您不应在ManageUserForm.js中导入Users.js ,因为Users.js本身通过UserCreator.js依赖于ManageUserForm.js

You can move MODES definition to ManageUserForm.js and import it in Users.js or better move it to a separate file completely.您可以将MODES定义移至ManageUserForm.js并将其导入Users.js或更好地将其完全移至单独的文件。

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

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