React Component Property Class (Proptypes) checksum

Source: Internet
Author: User



React Component Property Type (proptypes) checksum


Prop Verification


As applications grow larger, it is useful to ensure that components are used correctly. For this we introducepropTypes.React.PropTypesprovides a number of validators (validator) to validate the validity of incoming data. When invalid data is passed to props, the JavaScript console throws a warning. Note For performance reasons, only the development environment is validatedpropTypes. The following examples illustrate the differences between different validators:


React.createClass({
  propTypes: {
    // You can declare prop to be the specified JS primitive type. default
    // In the case, these props are all passable or not.
    OptionalArray: React.PropTypes.array,
    OptionalBool: React.PropTypes.bool,
    Optional Func: React.PropTypes.func,
    OptionalNumber: React.PropTypes.number,
    OptionalObject: React.PropTypes.object,
    OptionalString: React.PropTypes.string,

    // all objects that can be rendered: numbers,
    // String, DOM element or array containing these types.
    OptionalNode: React.PropTypes.node,

    // React element
    OptionalElement: React.PropTypes.element,

    // Declare prop as an instance of the class with JS's instanceof operator.
    optionalMessage: React.PropTypes.instanceOf(Message),

    // Use enum to restrict prop to accept only the specified value.
    OptionalEnum: React.PropTypes.oneOf([‘News‘, ‘Photos‘]),

    // one of the specified multiple object types
    optionalUnion: React.PropTypes.oneOfType([
      React.PropTypes.string,
      React.PropTypes.number,
      React.PropTypes.instanceOf(Message)
    ]),

    / / specify an array of type
    optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),

    // An object of the specified type of attribute
    OptionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),

    // object with a specific shape parameter
    OptionalObjectWithShape: React.PropTypes.shape({
      Color: React.PropTypes.string,
      fontSize: React.PropTypes.number
    }),

    // Add ʻisRequired` to any type later to make prop not nullable.
    requiredFunc: React.PropTypes.func.isRequired,

    // Any type that cannot be empty
    requiredAny: React.PropTypes.any.isRequired,

    // Customize the validator. An error object needs to be returned if validation fails. Do not directly
    // Use `console.warn` or throw an exception because `oneOfType` will fail.
    customProp: function(props, propName, componentName) {
      If (!/matchme/.test(props[propName])) {
        Return new Error(‘Validation failed!‘);
      }
    }
  },
  /* ... */
}); 
Default Prop value


React supports thepropsdefault values that are defined in a declarative manner.


 
 
var ComponentWithDefaultProps = React.createClass({
  getDefaultProps: function() {
    return {
      value: ‘default value‘
    };
  }
  /* ... */
});


When the parent does not have an incoming props, it isgetDefaultProps()guaranteed tothis.props.valuehave a default value, andgetDefaultPropsthe results of the notice are cached . Thanks to this, you can use props directly without having to write some repetitive or meaningless code manually.


Pass Props: Tips


There are some common React components that simply extend the HTML. Typically, you want to write less code to copy the props of the incoming component to the corresponding HTML element. At this point JSX's spread grammar will help you:


 
Var CheckLink = React.createClass({
   Render: function() {
     // This will copy all the props of the CheckList to <a>
     Return <a {...this.props}>{‘√ ‘}{this.props.children}</a>;
   }
});

React.render(
   <CheckLink href="/checked.html">
     Click here!
   </CheckLink>,
   document.getElementById(‘example‘)
);
Single sub-level


React.PropTypes.elementYou can qualify only one child to pass in.


 
 
var MyComponent = React.createClass({
  propTypes: {
    children: React.PropTypes.element.isRequired
  },

  render: function() {
    return (
      <div>
        {this.props.children} // There is only one element, otherwise an exception will be thrown. </div>
    );
  }

});
Mixins


Components are the best way to reuse code in React, but sometimes it is necessary to share some functionality among complex components. Sometimes referred to as cross-sectional concerns. React usedmixinsto solve this kind of problem.



A common scenario is that a component needs to be updated on a regular basis.setInterval()It is very easy to do it, but it is important to cancel the timer when it is not needed to save memory. React provides a life cycle approach to tell the component when it was created or destroyed. Here's a simple mixin to usesetInterval()and ensure that the timer is cleaned when the component is destroyed.


Var SetIntervalMixin = {
   componentWillMount: function() {
     This.intervals = [];
   },
   setInterval: function() {
     This.intervals.push(setInterval.apply(null, arguments));
   },
   componentWillUnmount: function() {
     This.intervals.map(clearInterval);
   }
};

Var TickTock = React.createClass({
   Mixins: [SetIntervalMixin], // reference mixin
   getInitialState: function() {
     Return {seconds: 0};
   },
   componentDidMount: function() {
     this.setInterval(this.tick, 1000); // call the method of mixin
   },
   Tick: function() {
     this.setState({seconds: this.state.seconds + 1});
   },
   Render: function() {
     Return (
       <p>
         React has been running for {this.state.seconds} seconds.
       </p>
     );
   }
});

React.render(
   <TickTock />,
   document.getElementById(‘example‘)
); 


The advantage of mixin is that if a component uses multiple mixin, and there are multiple mixin that define the same life-cycle methods (for example, multiple mixin need to do resource cleanup operations when the component is destroyed), all of these lifecycle methods are guaranteed to be executed. The order of the methods is executed by first executing the Mixin method in the order of Mixin introduction, and finally executing the method defined within the component.



React Component Property Class (Proptypes) checksum


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.