简体   繁体   English

在React propType定义中使用导入的模块

[英]Use imported modules in React propType definitions

I need Row s children to all be instances of the Col component: The following code worked when Row and Col were in the same file, but when I import Col into Row I get this error: Warning: Failed prop type: Cannot call a class as a function 我需要Row的所有子元素都是Col组件的实例:当Row和Col位于同一文件中时,以下代码可以工作,但是当我将Col导入Row时,出现此错误: Warning: Failed prop type: Cannot call a class as a function

How can variables and imports be used in propType definitions? 在propType定义中如何使用变量和导入? (building with webpack) (使用webpack构建)

 import React from 'react'; import PropTypes from 'prop-types'; import Col from './Col'; export default class Row extends React.Component { static propTypes = { children: PropTypes.oneOfType([ PropTypes.shape({ type: Col }), PropTypes.arrayOf(PropTypes.shape({ type: Col })) ]).isRequired, ...... 

As the React devs themselves admit here , there is no one way to define a prop type for a component. 正如React开发人员自己在这里承认的那样,没有一种方法可以为组件定义prop类型。

Perhaps the most generic possible option would be: 也许最通用的选择是:

PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.func])

If you're not concerned with strings (for native elements like "div") you can just do: 如果您不关心字符串(对于“ div”之类的本机元素),则可以执行以下操作:

React.PropTypes.func

And if you want to get very specific, see this answer: 如果您想变得非常具体,请参见以下答案:

React propTypes component class? React propTypes组件类?

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

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