The learning of React needs to continue. Recently, I am learning React while working on the unfinished project. The project was written by Vue, and a background management system is planned to be completed by React.

Grammar candy that some love and some hate — JSX

JSX profile

A lot of people don’t like React, largely because they don’t like JSX, so what exactly is JSX? First, don’t forget the basic philosophy of React — everything is JS, including the document structure. React uses a set of objects called react elements to build virtual DOM structures. The original way to create react elements is as follows:

const root = React.createElement('div', { className: 'main' }, 'I'm a div.');
Copy the code

It will eventually return an object that looks something like this:

const root = {
  type: 'div'.props: {
    className: 'main'.children: 'I'm a div.'}};Copy the code

Creating nodes one by one would be cumbersome. If each entire virtual DOM had to be created through react.createElement, it would be a lot of code, and the tree structure would not be intuitive and would not be development or maintenance-friendly. To solve this problem, a new xmL-like syntax extension was created, JSX.

The above code structure is changed to JSX and is written like this:

const root =(
  <div className="main">I'm a div</div>
);
Copy the code

This structure is familiar, but keep in mind that it is not an HTML template, it is JS and will eventually be completely escaped into pure JS code before execution, so there is no performance problem with using JSX.

JSX grammar

The standard syntax structure of JSX is very similar to THAT of XML. In particular, HTML attributes in JSX are written as small camel names, such as onclick. Another thing to note is that since class is a reserved word in JS, use className instead.

JSX When using JSX, always remember that it is a JS expression, so it can be just like a normal JS expression. Inside JSX, if you want to use expressions, you need to put them inside {}. This is JSX syntax, very simple, there is no need to memorize special instructions, everything can be handled just like js, here is a small example:

const item = this.newsList.map((news, index) = > (
    <li key={index}>
      <span>{news.title}</span>
      <span>{news.desc}</span>
      {news.image ? <img src="{news.image}"/> : null}
    </li>)); const list = (<ul>
    {item}
  </ul>
);
Copy the code

This is a particularly common use scenario in React development, where we get an array of data that needs to be rendered as a list. Don’t need to use any iteration in the react judgment related command syntax, as long as it can write js can understand the above logic: through the contents of the arrays map method of iteration, process the data in the callback function, rendering ChengXiang style, have a a list item, inserted into the list is complete data apply colours to a drawing. We can find that no matter in the iterative method or ternary expression and so on, as long as js grammar can be freely written inside, the degree of freedom is very high.

The basic unit of reusability – components

Why use components

Now that you know JSX, the next important concept is components. Components are not unique to React, and component-based development has many benefits. Components meet the requirements of high cohesion and low coupling. Each component is an independent entity that encapsulates views and logic.

A component can be thought of as a function call. A defined component is an abstract view of what we want it to look like by passing in related “parameters”. A component is the basic unit by which we reuse individual parts.

Components in React

The easiest way to define a component is to use JavaScript functions:

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

This is the simplest function definition component. The entire function call actually returns a

tag, but in particular, the content of the tag is not deterministic, it is determined by the parameters we pass in. This is component development. In React, instead of declaring a function component, it is most commonly used as follows:

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>; }}Copy the code

Here we use ES6 classes and inheritance to create a class that inherits from Component. This component has exactly the same effect as the previous one. Here we highlight some important concepts in the React component.

Core data state –state

What is the state? State. In the React component, state refers to the minimum set of states that a component’s UI can present. In React, the view layer is updated by handling state changes, and state is defined as a set of states. React data flows in one direction, so data can only flow from the model layer to the view layer. When it comes to specific implementation, a series of processing on the state will be automatically reflected in the view. We want to update the view, just update the state. Let’s look at a concrete example:

class ClickMe extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }
  clicked() {
    this.setState({
    	count: this.state.count + 1
    });
  }
  render() {
    return (
      <div onClick={()= >This.clicked ()}> hit me {this.state.count} times</div>); }}Copy the code

The effect of this component is to click on the text, and it will show you the number of clicks you have. The effect is very simple and I won’t take a screenshot. We’ll see later about the component lifecycle and click event binding. Initialize the state data in the constructor, place the state data on the page, and call the setState method when clicked to change the state data.

A few things to note about state:

  1. State cannot be changed directly. Modifying state directly does not update the view. The correct update method is to use setState to change the state value.
  2. Not all variables should be in state. Variables in state are intended to describe the state of the component itself, and do not need to be reflected in the view.
  3. State is the minimum set of states. The state information taken from the parent component is not its own state and cannot be placed in state. Things passed in from outside should be placed in props.

External pass attribute –props

Another very important component concept is props, which refers to properties that are passed in from the outside. React is the way a parent component communicates with its children. Here is a simple example:

class Child extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        {this.props.data}
      </div>); }}Copy the code

Using the component

<Child data="I am the data that is displayed."></Child>
Copy the code

When we define a Component, we receive props arguments in the constructor and pass them to the Component constructor using super. You can use the member variables props in the entire component class. The content of the props is passed in as an attribute when the parent calls the child. The whole thing is to control the flow of events from the parent element to the child element, so that we can use the component as a function call, passing it as a parameter.

When using props, data is transmitted in one direction. Data can only be transmitted from the parent component to the child component. If data needs to be transmitted in other directions, use other methods.

Component creation to destruction – life cycle

A React component needs to go through many stages from creation and operation to destruction. The system also provides hook methods corresponding to these stages. This means that the logic written in these methods will be automatically executed when the component reaches the corresponding stage.

Let’s take a look at each of these lifecycle approaches and the role they play

  1. GetDefaultProps and getInitialState. These methods are not visible if you use ES6 class inheritance to define components. Their job is to get the default props and initialize state before the component loads. Constructor must use super(props) in constructor; otherwise, an error will be reported.
  2. ComponentWillMount is called only once before a component is rendered. React is called only once after the parent component is called. If the state is set, react will render only after the state is set.
  3. Render (), the component rendering method, which returns the state of the component that was finally rendered. Its purpose is to render the component. State cannot be modified at this stage. As you can see from the diagram, in addition to being called for the first rendering, this method is also called when the component is updated, and is the core method of the component.
  4. ComponentDidMount, which is called after it’s been rendered gradually, is called only once, and this method for the child component is called before this method for the parent component, and the component is run after this method is done.
  5. ComponentWillReceiveProps (nextProps), component running stage, are called as component receives a new props, the function receives an object parameter (new props), the parent component happen render child component is invoked, Component first rendering does not trigger.
  6. ShouldComponentUpdate (nextProps, nextState), which is called when the component is running and receives a new props or state. This method returns true by default, and can be controlled to return false to prevent component rerendering.
  7. ComponentWillUpdate, the component run phase, is called when it is ready to re-render the component, to do some pre-render work, the first time the component renders is not triggered.
  8. ComponentDidUpdate, component run state, called after the component rerenders, the first time the component renders will not trigger.
  9. ComponentWillUnmount, called before the component is unloaded, does some cleanup before the end.

The React lifecycle covers the basic concepts of the React component.

Behavior and interaction — event binding

There is one problem with binding events in React. If you use ES6’s class method, the event handler function this is not bound by default. You need to manually bind this pointer. Here’s an example of an error:

class EventTest extends React.Component {
  clicked() {
    console.log('clicked');
  }
  render() {
    return (
      <div onClick={this.clicked}>Am I</div>); }}Copy the code

Clicked on me, it does print correctly and seems fine, but if you try to print this, you will find undefined.

We can’t use member variables and methods, and we can’t call built-in methods. This is not what we expected, so we need to manually bind this pointer.

class EventTest extends React.Component {
  clicked() {
    console.log('clicked');
  }
  render() {
    return (
      <div onClick={this.clicked.bind(this)}>Am I</div>); }}Copy the code

Simply add bind(this), which is a common way to bind this, to achieve the desired effect. Alternatively, you can use the arrow function to automatically bind this, which is perfectly fine:

class EventTest extends React.Component {
  clicked() {
    console.log('clicked');
  }
  render() {
    return (
      <div onClick={()= >I enclosing clicked ()} > point</div>); }}Copy the code

Use Clicked as a function returned from arrow functions. This binding can also be implemented using the auto-binding feature inside arrow functions. Here’s another way to write it:

class EventTest extends React.Component {
  clicked = (a)= > {
    console.log('clicked');
  }
  render() {
    return (
      <div onClick={this.clicked}>Am I</div>); }}Copy the code

This method is an experimental syntax in the new ES standard, and it is also available thanks to the Babel translation. It is also mentioned on the official website, but is not widely used because the new standard is still immature.


Learn react Native, virtual DOM, DIff algorithm, CSS-IN-JS, react Router, Redux, and React Native. The following is slowly summarized with learning.