美文网首页React
013|React之类型检察

013|React之类型检察

作者: 中年小钢炮 | 来源:发表于2017-06-07 11:38 被阅读7次

    在React中,可以添加对props类型的检察。如:

    import PropTypes from 'prop-types';
    
    class Greeting extends React.Component {
      render() {
        return (
          <h1>Hello, {this.props.name}</h1>
        );
      }
    }
    
    Greeting.propTypes = {
      name: PropTypes.string
    };
    

    觉见的ProtoTypes:

    import PropTypes from 'prop-types';
    
    MyComponent.propTypes = {
      // You can declare that a prop is a specific JS primitive. By default, these
      // are all optional.
      optionalArray: PropTypes.array,
      optionalBool: PropTypes.bool,
      optionalFunc: PropTypes.func,
      optionalNumber: PropTypes.number,
      optionalObject: PropTypes.object,
      optionalString: PropTypes.string,
      optionalSymbol: PropTypes.symbol,
    
      // Anything that can be rendered: numbers, strings, elements or an array
      // (or fragment) containing these types.
      optionalNode: PropTypes.node,
    
      // A React element.
      optionalElement: PropTypes.element,
    
      // You can also declare that a prop is an instance of a class. This uses
      // JS's instanceof operator.
      optionalMessage: PropTypes.instanceOf(Message),
    
      // You can ensure that your prop is limited to specific values by treating
      // it as an enum.
      optionalEnum: PropTypes.oneOf(['News', 'Photos']),
    
      // An object that could be one of many types
      optionalUnion: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.number,
        PropTypes.instanceOf(Message)
      ]),
    

    React中还可以通过defaultTypes来设置默认参数:

    class Greeting extends React.Component {
      render() {
        return (
          <h1>Hello, {this.props.name}</h1>
        );
      }
    }
    
    // Specifies the default values for props:
    Greeting.defaultProps = {
      name: 'Stranger'
    }; // 设置默认props值
    

    因为函数式组件不支持state、ref,一般不建议使用函数式组件。

    想学计算机技术吗?需要1对1专业级导师指导吗?想要团队陪你一起进步吗?欢迎加我为好友!微信号:iTekka。

    相关文章

      网友评论

        本文标题:013|React之类型检察

        本文链接:https://www.haomeiwen.com/subject/yfvofxtx.html