Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

props validate属性验证 #5

Open
mqy1023 opened this issue Sep 27, 2016 · 0 comments
Open

props validate属性验证 #5

mqy1023 opened this issue Sep 27, 2016 · 0 comments

Comments

@mqy1023
Copy link
Owner

mqy1023 commented Sep 27, 2016

实例

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》

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant