反应 propTypes 组件 class?

React propTypes component class?

如何验证提供的道具是一个组件 class(不是实例)?

例如

export default class TimelineWithPicker extends React.PureComponent {

    static propTypes = {
        component: PropTypes.any, // <-- how can I validate that this is a component class (or stateless functional component)?
    };

    render() {
        return (
            <this.props.component {...this.props} start={this.state.start}/>
        );
    }
}

已编辑:将 React 的 FancyButton 示例添加到 codesandbox 以及与 React 16.3 中的新 React.forwardRef api 一起使用的自定义道具检查功能。 React.forwardRef api returns 具有 render 功能的对象。我正在使用以下自定义道具检查器来验证此道具类型。 - 感谢 Ivan Samovar 注意到这一需求。

FancyButton: function (props, propName, componentName) {
  if(!props[propName] || typeof(props[propName].render) != 'function') {
    return new Error(`${propName}.render must be a function!`);
  }
}

您需要使用 PropTypes.element。实际上... PropType.func 适用于无状态功能组件和 class 组件。

我已经制作了一个沙箱来证明它有效...考虑到我一开始给你的信息是错误的,我认为这是需要的。对此非常抱歉!

正在工作sandbox example

这是万一 link 死机的测试代码:

import React from 'react';
import { render } from 'react-dom';
import PropTypes from "prop-types";

class ClassComponent extends React.Component {
  render() {
    return <p>I'm a class component</p>
  }
}

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;

const FSComponent = () => (
    <p>I'm a functional stateless component</p>
);

const Test = ({ ClassComponent, FSComponent, FancyButton }) => (
  <div>
    <ClassComponent />
    <FSComponent />
    <FancyButton />
  </div>
);
Test.propTypes = {
  ClassComponent: PropTypes.func.isRequired,
  FSComponent: PropTypes.func.isRequired,
  FancyButton: function (props, propName, componentName) {
    if(!props[propName] || typeof(props[propName].render) != 'function') {
      return new Error(`${propName}.render must be a function!`);
    }
  },
}

render(<Test
         ClassComponent={ ClassComponent }
         FSComponent={ FSComponent }
         FancyButton={ FancyButton } />, document.getElementById('root'));

对于使用 PropTypes >= 15.7.0 的任何人,在此 pull request and was released on february 10, 2019 中添加了一个新的 PropTypes.elementType

此道具类型支持所有组件(本机组件、无状态组件、有状态组件、前向引用 React.forwardRef、上下文 providers/consumers)。

当不是任何这些元素时它会发出警告,当传递的 prop 是一个元素(PropTypes.element)而不是类型时它也会发出警告。

您终于可以像使用任何其他道具类型一样使用它了:

const propTypes = {
    component: PropTypes.elementType,
    requiredComponent: PropTypes.elementType.isRequired,
};