React PropTypes:允许一个道具有不同类型的 PropTypes

React PropTypes: Allow different types of PropTypes for one prop

我有一个组件接收其大小的道具。 prop 可以是字符串或数字,例如:"LARGE"17.

我可以让 React.PropTypes 知道在 propTypes 验证中这可以是其中之一吗?

如果我不指定类型,我会收到警告:

prop type size is invalid; it must be a function, usually from React.PropTypes.

MyComponent.propTypes = {
    size: React.PropTypes
}
size: PropTypes.oneOfType([
  PropTypes.string,
  PropTypes.number
]),

了解更多:Typechecking With PropTypes

import React from 'react';              <--as normal
import PropTypes from 'prop-types';     <--add this as a second line

    App.propTypes = {
        monkey: PropTypes.string,           <--omit "React."
        cat: PropTypes.number.isRequired    <--omit "React."
    };

    Wrong:  React.PropTypes.string
    Right:  PropTypes.string

这可能对你有用:

height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

出于文档目的,最好列出合法的字符串值:

size: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.oneOf([ 'SMALL', 'LARGE' ]),
]),

这是使用多属性和单一属性的专业示例。

import React, { Component } from 'react';
import { string, shape, array, oneOfType } from 'prop-types';

class MyComponent extends Component {
  /**
   * Render
   */
  render() {
    const { title, data } = this.props;

    return (
      <>
        {title}
        <br />
        {data}
      </>
    );
  }
}

/**
 * Define component props
 */
MyComponent.propTypes = {
  data: oneOfType([array, string, shape({})]),
  title: string,
};

export default MyComponent;