react-with-es6 icon indicating copy to clipboard operation
react-with-es6 copied to clipboard

props validate属性验证

Open mqy1023 opened this issue 8 years ago • 0 comments

实例

import React, { Component, PropTypes } from 'react';

export default class MyPropsDemo extends Component {
  render() {
    const {
      collapsed = '',
      num = '',
      itemClassName = '',
      nodeLabel,
      children,
      ...rest,
    } = this.props;

    return(<div>{children}</div>);
  }
}

MyPropsDemo.propTypes = {
  collapsed: PropTypes.bool,
  nodeLabel: PropTypes.node.isRequired,
  num: PropTypes.number,
  itemClassName: PropTypes.string,
  onClick: PropTypes.func,
  children: PropTypes.oneOfType([
      PropTypes.node,
      PropTypes.arrayOf(PropTypes.node)
    ]).isRequired,
};

// Specifies the default values for props:
MyPropsDemo.defaultProps = {
  collapsed: false
};

Prop Validation

  • a specific js primitive
    • optionalArray: React.PropTypes.array,
    • optionalBool: React.PropTypes.bool,
    • optionalFunc: React.PropTypes.func,
    • optionalNumber: React.PropTypes.number,
    • optionalObject: React.PropTypes.object,
    • optionalString: React.PropTypes.string,
    • optionalSymbol: React.PropTypes.symbol
  • Anything that can be rendered: numbers, strings, elements or an array (or fragment) containing these types.
    • optionalNode: React.PropTypes.node
  • An array of a certain type
    • optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number)
  • An object that could be one of many types
  optionalUnion: React.PropTypes.oneOfType([
    React.PropTypes.string,
    React.PropTypes.number,
    PropTypes.arrayOf(PropTypes.node)
  ])

You can chain any of the above with isRequired to make sure a warning is shown if the prop isn't provided.

参考链接

1、facebook官网《Prop Validation》

mqy1023 avatar Sep 27 '16 02:09 mqy1023