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

React丨PropTypes & defaultProps #3

Closed
wangjianuo opened this issue Jun 17, 2019 · 0 comments
Closed

React丨PropTypes & defaultProps #3

wangjianuo opened this issue Jun 17, 2019 · 0 comments

Comments

@wangjianuo
Copy link
Owner

简单示例

import PropTypes from 'prop-types';

class Greeting extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}

Greeting.propTypes = {
  name: PropTypes.string
};

PropTypes 解析

import PropTypes from 'prop-types';

MyComponent.propTypes = {
  // 可以定义一个属性是特定的JS类型(Array,Boolean,Function,Number,Object,String,Symbol)。默认情况下,这些都是可选的。
  optionalArray: PropTypes.array,
  optionalBool: PropTypes.bool,
  optionalFunc: PropTypes.func,
  optionalNumber: PropTypes.number,
  optionalObject: PropTypes.object,
  optionalString: PropTypes.string,
  optionalSymbol: PropTypes.symbol,

  // 指定类型为:任何可以被渲染的元素,包括数字,字符串,react 元素,数组,fragment。
  optionalNode: PropTypes.node,

  // 一个react 元素
  optionalElement: PropTypes.element,

  // 可以类型为某个类的实例,这里使用JS的instanceOf操作符实现
  optionalMessage: PropTypes.instanceOf(Message),

  // 枚举类型:你可以把属性限制在某些特定值之内
  optionalEnum: PropTypes.oneOf(['News', 'Photos']),

  // 指定多个类型:你也可以把属性类型限制在某些指定的类型范围内
  optionalUnion: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.instanceOf(Message)
  ]),

  // 指定某个类型的数组
  optionalArrayOf: PropTypes.arrayOf(PropTypes.number),

  // 指定类型为对象,且对象属性值是特定的类型
  optionalObjectOf: PropTypes.objectOf(PropTypes.number),

  // 指定类型为对象,且可以规定哪些属性必须有,哪些属性可以没有
  optionalObjectWithShape: PropTypes.shape({
    color: PropTypes.string,
    fontSize: PropTypes.number
  }),

  //加上isReqired限制,可以指定某个属性必须提供,如果没有出现警告。
  requiredFunc: PropTypes.func.isRequired,
  requiredAny: PropTypes.any.isRequired,

  // 也可以指定一个自定义的验证器。如果验证不通过,它应该返回Error对象,而不是`console.warn `或抛出错误。`oneOfType`中不起作用。
  customProp: function(props, propName, componentName) {
    if (!/matchme/.test(props[propName])) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  },

  // 也可以提供一个自定义的验证器 arrayOf和objectOf。如果验证失败,它应该返回一个Error对象。
  // 验证器用来验证数组或对象的每个值。验证器的前两个参数是数组或对象本身,还有对应的key。
  customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
    if (!/matchme/.test(propValue[key])) {
      return new Error(
        'Invalid prop `' + propFullName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  })
};
import PropTypes from 'prop-types';

class MyComponent extends React.Component {
  render() {
    // This must be exactly one element or it will warn.
    const children = this.props.children;
    return (
      <div>
        {children}
      </div>
    );
  }
}

MyComponent.propTypes = {
  children: PropTypes.element.isRequired
};

Default Prop Values

class Greeting extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}

// Specifies the default values for props:
Greeting.defaultProps = {
  name: 'Stranger'
};

// Renders "Hello, Stranger":
ReactDOM.render(
  <Greeting />,
  document.getElementById('example')
);
class Greeting extends React.Component {
  static defaultProps = {
    name: 'stranger'
  }

  render() {
    return (
      <div>Hello, {this.props.name}</div>
    )
  }
}

参考:
https://reactjs.org/docs/typechecking-with-proptypes.html

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