Component creation and value transfer of react 16 tutorial

Keywords: React Vue Fragment

assembly

Create component

There are three types of components: a stateful component, a stateless component and a stateful component. The stateful component will be described later

Stateful component

As the name implies, stateful component has its own state and life cycle, and the positioning of stateful component mainly deals with some logical interaction operations and data processing operations, which is more inclined to logical processing interaction.

It can be created through Class, but the created Class will inherit Component

Such As:

// Introducing react
import React from 'react';
// Introduce component css Style
import './index.css';
// Creating component objects from classes
// But you need to create a class pair React.Component To inherit
// And throw out the created components
export default class home extends React.Component {
    constructor(){
        // Parameters from parent component
        super(props)
        // Where data is stored in a component
        this.state = {
            value: "wzy"
        }
    }
    handleChange(e){
        this.setState({
            value : e.target.value
        })
    }
    // Using jsx to return component structure in render
    render(){
        return(
            <div>
                // Binding data needs to be bound with single curly braces
                <p>{this.state.value}</p>
            </div>
        )
    }   
}

Stateless component

The stateless component is just the opposite of the stateful component. The stateless component only accepts the props parameter and does not perform logical operation. It is mainly a template, which shows the data in props. Stateless components should maintain the purity of the template to facilitate component reuse.

Such As:

var Header = (props) = (
    <div>{props.xxx}</div>
);

Reference component

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Home from './home';
import * as serviceWorker from './serviceWorker';
// import the created components and write jsx here for use
ReactDOM.render(
  <React.StrictMode>
    <div>
      <Home />
      <App />
    </div>
  </React.StrictMode>,
  document.getElementById('root')
);
serviceWorker.unregister();

Combined components

Components can reference other components in their output. This allows us to abstract any level of detail with the same component. Buttons, forms, dialog boxes, even the contents of the entire screen: in a React application, these are usually represented as components.

import React from 'react';
import { render } from 'react-dom';
const Bom1 = (props) =>{
    return(<p>{props.name}</p>)
}
const Box = ()=>{
    return(
        <div>
            <Bom1 name='1'/>
            <Bom1 name='2'/>
            <Bom1 name='3'/>
            <Bom1 name='4'/>
        </div>
    )
}
render(
  <Box />,
  document.getElementById('root')
);

Props is read-only

Components, whether declared by function or class, must not modify their props.

function sum(a, b) {
  return a + b;
}

Such a function is called a "pure function" because it does not attempt to change the input parameter, and the same input parameter always returns the same result under multiple calls.

function sum2(account,num){
    account.total -= num;
}

Such a function is not a pure function. Because it changes its parameters.

All React components must protect their props as pure functions.

Special attention is needed, this.props.children It is a special prop, usually composed of subcomponents in JSX expressions, rather than defined by the component itself.

Component value transfer

Parent child component value transfer

   // Parent component
   
   import React from 'react';
   import ReactDOM from 'react-dom';
   import './index.css';
   import App from './App';
   import Home from './home';
   import * as serviceWorker from './serviceWorker';
   // import the created components and write jsx here for use
   ReactDOM.render(
     <React.StrictMode>
       <div>
         <Home name='1'/>
         <App />
       </div>
     </React.StrictMode>,
     document.getElementById('root')
   );
   serviceWorker.unregister();
   
   // Subcomponent
   
   import React from 'react';
   import './index.css';
   export default class home extends React.Component {
       // The value transferred from the parent component is stored in props
       constructor(props){
           super()
           this.state = {
               value: "wzy"
           }
       }
       handleChange(e){
           this.setState({
               value : e.target.value
           })
       }
       render(){
           return(
               <div>
                   {this.props.name}
               </div>
           )
       }   
   }

Pass value verification

// Introduce calibration module
import PropTypes from 'prop-types';
MyComponent.propTypes = {
  // You can declare properties as JS native types, by default
  // These properties are optional.
  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, elements, or arrays)
  // (or Fragment) also contains these types.
  optionalNode: PropTypes.node,

  // A React element.
  optionalElement: PropTypes.element,

  // A React element type (that is, MyComponent).
  optionalElementType: PropTypes.elementType,

  // You can also declare prop as an instance of a class, using
  // The instance of operator of JS.
  optionalMessage: PropTypes.instanceOf(Message),

  // You can make your prop a specific value and specify it as
  // Enumeration type.
  optionalEnum: PropTypes.oneOf(['News', 'Photos']),

  // An object can be any one of several types
  optionalUnion: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.instanceOf(Message)
  ]),

  // You can specify that an array consists of elements of a certain type
  optionalArrayOf: PropTypes.arrayOf(PropTypes.number),

  // You can specify that an object consists of values of a certain type
  optionalObjectOf: PropTypes.objectOf(PropTypes.number),

  // You can specify that an object consists of specific type values
  optionalObjectWithShape: PropTypes.shape({
    color: PropTypes.string,
    fontSize: PropTypes.number
  }),
  
  // An object with warnings on extra properties
  optionalObjectWithStrictShape: PropTypes.exact({
    name: PropTypes.string,
    quantity: PropTypes.number
  }),   

  // You can add 'isRequired' after any PropTypes property to ensure that
  // When the prop is not provided, a warning message is printed.
  requiredFunc: PropTypes.func.isRequired,

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

  // You can specify a custom validator. It should return an Error object when validation fails.
  // Please do not use` console.warn `Or throw an exception, because this will not work in 'onOfType'.
  customProp: function(props, propName, componentName) {
    if (!/matchme/.test(props[propName])) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  },

  // You can also provide a custom 'arrayOf' or 'objectOf' verifier.
  // It should return an Error object when validation fails.
  // The validator validates each value in the array or object. First two parameters of verifier
  // The first is the array or the object itself
  // The second is their current 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.'
      );
    }
  })
};

Pass value from child component to parent component

    // Parent component
    import React from 'react';
    import Child  from "../child"
    export default class Parent extends React.Component{
        constructor(props){
            super(props);
        }
        render(){
            return(
                <div>
                    <Child cb={this.getChildState.bind(this)}></Child>
                </div>
            )
        }
        getChildState(value){
            console.log('parent',value)
        }
    }

The parent component passes in a custom field to pass in the custom function and bind this to get the data of the child component. The default value of the custom function is the data passed from the child component

    // Subcomponent
    import React from 'react';
    export default class child extends React.Component{
        constructor(props){
            super(props)
            this.state={
                sendParent:"11111"
            }
            this.props.cb(this.state.sendParent)
        }
        render() {
          return (
            <div>
              {this.state.sendParent}
            </div>
          )
        };
    }

The child component passes the data to be sent into the parameter by calling the custom function passed from the parent component

Value transfer of brother components

In fact, it is similar to vue. In vue, the value of the sibling components is passed through a bus function. react, on the other hand, changes the data into a parent component. After the child component transfers the data to the parent component, the parent component transfers the data to another child component

context passing value

I haven't read this for a while.... Back filling

Posted by boonika on Sun, 07 Jun 2020 20:26:13 -0700