[英]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 .你有一个循环依赖。
Users.js
from App.js
.App.js
Users.js
Users.js
imports UserCreator.js
.Users.js
导入UserCreator.js
。UserCreator.js
imports ManageUserForm.js
.UserCreator.js
导入ManageUserForm.js
。ManageUserForm.js
imports Users.js
againUsers.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.