反应propTypes组件类?

mpe*_*pen 17 reactjs

如何验证提供的prop是组件类(而不是实例)?

例如

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}/>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

Kyl*_*son 24

编辑:将React的FancyButton示例添加到codesandbox以及自定义道具检查功能,该功能与React.forwardRefReact 16.3中的新api一起使用.该React.forwardRefAPI返回一个对象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!`);
  }
}
Run Code Online (Sandbox Code Playgroud)

你会想要使用 PropTypes.element.实际上...... PropType.func适用于无状态功能组件和类组件.

我已经制作了一个沙盒来证明这是有效的...想想这是需要考虑到我最初给你错误的信息.非常抱歉!

工作沙箱示例!

以下是测试代码,以防链接失效:

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'));
Run Code Online (Sandbox Code Playgroud)

  • 对于不同的类型也使用`oneOfType`:`PropTypes.oneOfType([...])` (2认同)

Jos*_*lva 10

对于任何使用PropTypes >= 15.7.0新功能的人PropTypes.elementType,都会在此拉取请求中添加,并于20192月10日发布。

此prop类型支持所有组件(本机组件,无状态组件,有状态组件,前向引用React.forwardRef,上下文提供者/消费者)。

并且当所有元素都不是时,它会发出警告,并且传递的prop是元素(PropTypes.element)而不是类型时,它也会发出警告。

最后,您可以像使用其他道具类型一样使用它:

const propTypes = {
    component: PropTypes.elementType,
    requiredComponent: PropTypes.elementType.isRequired,
};
Run Code Online (Sandbox Code Playgroud)