React device outline talk

React is a front-end component-based development pedigree, this development mode completely solve the front-end components with complex pain points. Today, we take a look React component development.

Students usually from the front entry Vue, Vue used as <template>component development mode makes it easier for the front end of a smooth transition. Vue assembly is very simple, in general, a .vuefile is a component. Like webpackthe modular development, a file is a component. We are also very easy to use components by ES6 the importimport registration (components), can be used directly.

Simply put above the Vue component model, in fact, React of use is similar, after all, is to learn from its components thought. The most obvious difference is declaratively, React use the JSX grammar, which makes React become very flexible. Of course, the flexible use also means that the user's brain needs sufficient flexibility, thereby increasing the difficulty of getting started. 6 people playing are really like, entry is not really can not understand why the label is written html js inside it.

Well, so much pull above, following on to explore how React assembly ...

React assembly base

In the beginning, let us first look at how the components React definition and classification.

Component Definition

There are two ways React statement component ( React.createClassdeprecated): function class components and assemblies. What is the difference between them is it?

If a component only render the page according to props, no internal state of the state, we can use components to achieve functional form . In other words, simply a function of the components responsible for displaying data, it there is no life-cycle function and state, and can not do business logic processing.

Component function (stateless component):

import React from "react";

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

class components:

import React, { Component } from "react";

class Welcome extends React.Component {
  constructor(props) {
    super(props);
    // 设置 initial state
    this.state = {
      text: props.initialValue || 'placeholder'
    };
    // ES6 类中函数必须手动绑定
    this.handleChange = this.handleChange.bind(this);
  }
  handleClick(event) {
    this.setState({
      text: event.target.value
    });
  }
  componentDidMount() {
  // do something
  }
  componentWillUnmount() {
    clearInterval(this.timer);
  }
  render() {
    return (
      <div>
        <h1>Hello, {this.props.name}</h1>;
        <button onClick={this.handleClick}></button>
      </div>
    )
  }
}

note:

  1. React self-righteousness of the components are given capital letter
  2. Props are read-only, if you want to change the state, the state is required to enhance the

Components Category

React component into two types: display assembly and the container assembly. After the components into these two categories, you will find them more easily be reused and understanding. Typically, the display component responsible for displaying the content of the container component responsible for processing business logic. The above is not a function of the difference between like class components and assembly.

Container components and display components nouns from redux Chinese documents.

  • Display assembly

    1. Showing the effect of an attention page (appearance)

    2. Internal components and containers can include display components, typically contain some of their own DOM tags and style (style)

    3. Typically allowed to contain other components by way this.props.children

    4. Other parts of the application no dependencies, or store operation Flux e.g.

    5. Do not care how the data is loaded and changes

    6. Data and can only receive a callback (callback) operation by way of props

    7. Few have their own state, even if there is a state representative UI

    8. Unless the component needs to be its own state, the life cycle or do some performance optimizations written functional components

Example:Page、Header、Sidebar、List、UserInfo...

  • The container assembly

    1. Concern is how the application works

    2. The internal may comprise a container assembly and display assembly, but usually no own DOM marker (in addition to some of the packaging div), and not having any style

    3. Provide data and behavior to other display component or components of the container

    4. Call Flux operations and provides them to the callback function as a display assembly

    5. There is often a state, because they tend as a data source

    6. Commonly used to generate high order components , e.g. React Redux a connect (), Relay of createContainer () Flux Utils or the Container.create (), instead of manually prepared

    Example:UserPage、StoryContainer、 FollowedUserList...

  • advantage
    1. Better separation of concerns. This way to write components that can better understand your application and UI
    2. High reusability, display assembly may be used for a plurality of different data sources.
    3. The display assembly is your palette, you can put them into a single page, without affecting applications, allowing designers to adjust the UI.
    4. This forces you to extract such as "Layout Components" sidebar, page context menus and use this.props.children, instead of copying the same tag in multiple containers and layout components.

Now, we already know the difference display assembly and container components. Container components tend to have a state, the components tend to show no state, this is not mandatory, because the container components and display components can be stateful. Typically, display assembly wrapped container assembly, since the inner container assembly business logic, sends the processed data to the display assembly.

When unimportant or that it is hard to distinguish, not to show the separation vessel components and assemblies as dogma, if you are not sure the component is a container component or display assembly is, for the time being not to separate, written to show the components of it.

Higher-order components

Higher-order component (HOC) are React for reuse component logic an advanced skills. React HOC itself is not part of an API, which is based on a combination of characteristics of the design pattern which is formed React.

Specifically, the high-order parameter for a component assembly, the function returns the value of the new component.

const EnhancedComponent = higherOrderComponent(WrappedComponent);

Components are converted to props UI, high order component is converted to another component assembly . Remember the above said container components? Higher-order functions and container components are similar, the same logic can be pulled out of the multiplex, we need to show the package components.

JavaScript higher order components from higher order function - higher order function is a function that accepts as input or output function. A high-order component is just as the input component group receiving and returning assembly . Did not seem anything, then what can bring higher-order components for us? First, look at how higher-order components is achieved, in general, a higher order mode has the following three components:

Property Broker

Operating props

const HOC = (WrappedComponent) =>
    class WrapperComponent extends Component {
      render() {
        const newProps = {
          name: 'HOC'
        }
        return <WrappedComponent
          {...this.props}
          {...newProps}
        />;
      }
    }

To pass before we see to be WrappedComponent package component properties passed to the first component (WrapperComponent) of high-order component returns, so we gained control of the props (which is why this method is called property broker). We can follow the need for incoming props to add, delete, modify (of course, modify the risk caused by the need to control your own).

Abstract state

In the case of property broker, we can state will be wrapped assembly (WrappedComponent) mentioned in the package components, to achieve a common example is not controlled component to the controlled components change.

class WrappedComponent extends Component {
    render() {
        return <input name="name" {...this.props.name} />;
    }
}

const HOC = (WrappedComponent) =>
    class extends Component {
        constructor(props) {
            super(props);
            this.state = {
                name: '',
            };

            this.onNameChange = this.onNameChange.bind(this);
        }

        onNameChange(event) {
            this.setState({
                name: event.target.value,
            })
        }

        render() {
            const newProps = {
                name: {
                    value: this.state.name,
                    onChange: this.onNameChange,
                },
            }
            return <WrappedComponent {...this.props} {...newProps} />;
        }
    }

By high-order components, we will not be controlled in the example above components (WrappedComponent) successfully into the controlled components.

Combinations

const HoC = (WrappedComponent, LoginView) => {
    const WrappingComponent = () => {
        const {user} = this.props;  
        if (user) {
            return <WrappedComponent {...this.props} />
        } else {
            return <LoginView {...this.props} />
        }
    };
    return WrappingComponent;
};

The code has two components, WrappedComponent and LoginView, if the incoming propsexists user, then the normal display of WrappedComponent component or components LoginView display, allowing users to log on. HoC parameters can be passed into multiple, new components deliver customized behavioral multiple components, such as displaying the main page user login status, unknown to display the login screen; when rendering a list of incoming and Loading List component, add new components the load behavior.

Reverse Inheritance

Reverse Inheritance refers to the components of the assembly before returning to inherit

Operating props and state

In some cases, we may need to pass some parameters for high-end property, then we can pass parameters in the form of curried, for example:

import React, { Component } from 'React';

const HOCFactoryFactory = (...params) => {
    // 可以做一些改变 params 的事
    return (WrappedComponent) => {
        return class HOC extends Component {
            render() {
                return <WrappedComponent {...this.props} />;
            }
        }
    }
}

You can use the following manner:

HOCFactoryFactory(params)(WrappedComponent)

This approach is not very similar to the React-Reduxlibrary connectfunction, because connectis a similar kind of higher-order functions. Reverse the order of succession is different from calling the property broker, rendering the order of components is: first WrappedComponent again WrapperComponent (ComponentDidMount the execution time). The order also unloaded again first WrappedComponent WrapperComponent (ComponentWillUnmount the execution time).

to sum up

Written to be over here, very briefly describes the components of React. The article is short and I hope that you probably understand some of the characteristics React components. To sum up:

  • React declaratively using two components: Function Component and class components. Function components only render a return function, class components can have a life-cycle and other business logic handler

  • React divided into two components from the use of the form: The display assembly and container components. Basic principles: container components are responsible for data acquisition, display component is responsible for displaying information in accordance with props

  • React higher-order component is the parameter for the component, the return value is a function of new components. The advantage of this is that you can pull away some of the same business logic to facilitate reuse. It acts like Mixin, but avoid the Mixin side effects.

Guess you like

Origin www.cnblogs.com/chenwenhao/p/11968176.html