简体   繁体   中英

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

How can variables and imports be used in propType definitions? (building with 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.

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:

React.PropTypes.func

And if you want to get very specific, see this answer:

React propTypes component class?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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