Organize the learning notes of React - Components

1. Define components

1) function components

function GreateH(props){
    return <div>
        <h2>hello,{props.name}</h2>
    </div>
}
ReactDOM.render(<GreateH name="kristy"/>, document.getElementById('root'));

2) components

class GreateH extends React.Component{
    render(){
        return <div>
            <h2>hello,{this.props.name}</h2>
           </div>
    }
}
ReactDOM.render(<GreateH name="kristy"/>, document.getElementById('root'));

The component name must start with an uppercase letter.

3) write the component in a js file separately, and define or import it when using.
title.js here you need to export the components

import React from "react";
class GreateH extends React.Component{
    render(){
        return <div>
            <h2>hello,{this.props.name}</h2>
        </div>
    }
}
export default GreateH;

Must be introduced in index.js

import React from 'react';
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
import Title from './components/title'
ReactDOM.render(<Title name="kristy"/>, document.getElementById('root'));
serviceWorker.unregister();

4) the return value of a component can only have one root element.

2. props default value

1) set the default value of the functional component and the value of the static property defaultProps.

function GreateH(props){
   return <div>
         <h2>hello,{props.name}</h2>
     </div>
}
GreateH.defaultProps = {name:'CoCo'};
ReactDOM.render(<GreateH />, document.getElementById('root'));

2) set the default value for class components.
The first is to set the value of defaultProps, the static property of a class, the same as a function component.
The second is defined in the class:

class GreateH extends React.Component{
   //Defined here
    static defaultProps = {name:'CoCo'};
    render(){
        return <div>
            <h2>hello,{this.props.name}</h2>
        </div>
    }
}

3. Use PropTypes for type checking

1) run NPM I prop types -- save to install prop types and import import proptypes from 'prop types' into the component.
If an error is reported during restart, you can delete the dependency package and install it again.
2) verification example:

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

PropTypes
Here are examples of using different validators:

MyComponent.propTypes = {
  // You can declare properties as the following JS native types
  optionalArray: PropTypes.array,
  optionalBool: PropTypes.bool,
  optionalFunc: PropTypes.func,
  optionalNumber: PropTypes.number,
  optionalObject: PropTypes.object,
  optionalString: PropTypes.string,
  optionalSymbol: PropTypes.symbol,

  // Any element that can be rendered (including numbers, strings, subelements, or arrays).
  optionalNode: PropTypes.node,

  // A React element
  optionalElement: PropTypes.element,

  // You can also declare the property as an instance of a class. Here you use JS's
  // The instanceof operator implementation.
  optionalMessage: PropTypes.instanceOf(Message),

  // You can also limit the value of your property to a specific value
  optionalEnum: PropTypes.oneOf(['News', 'Photos']),

  // Restrict objects that are one of the enumerated types
  optionalUnion: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.instanceOf(Message)
  ]),

  // An array of specified element types
  optionalArrayOf: PropTypes.arrayOf(PropTypes.number),

  // An object of the specified type
  optionalObjectOf: PropTypes.objectOf(PropTypes.number),

  // An object that specifies a property and its type
  optionalObjectWithShape: PropTypes.shape({
    color: PropTypes.string,
    fontSize: PropTypes.number
  }),

  // You can also add 'isRequired' after any PropTypes property` 
  // Suffix, so that if the parent component of this property is not provided, a warning message will be printed
  requiredFunc: PropTypes.func.isRequired,

  // Any type of data
  requiredAny: PropTypes.any.isRequired,

  // You can also specify a custom validator. It should return when validation fails
  // An Error object instead of 'console.warn' or throwing an exception.
  // But it doesn't work in 'oneOfType'.
  customProp: function(props, propName, componentName) {
    if (!/matchme/.test(props[propName])) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  },

  // But you can provide a custom 'arrayOf' or 'objectOf'` 
  // Validator, which should return an Error object when validation fails. It is used.
  // To verify each value of an array or object. The first of the first two arguments of the verifier is an array
  // Or the object itself, and the second is their corresponding 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.'
      );
    }
  })
};

More detailed instructions can be found in the documentation: https://react.docschina.org/docs/typechecking-with-proptypes.html

Tags: Javascript React npm

Posted on Tue, 03 Dec 2019 12:33:42 -0500 by peterg012