React notes for getting started

Write in front, the author is shallow, write this article to do reference only! Please forgive me if I am wrong.

Reading this article, I believe you may have some vue.js learning experience. Besides, you have some programming ability, and I believe you have the idea to learn React. I am read the React of official documentation (https://react.docschina.org/), and then by looking at [jspang video] (https://jspang.com/detailed?id=46#toc21), step by step.

preface

Sharing Teacher Winter once said a point of view: for any language, it must be a process of “using standard grammar to express specific semantics and finally operating time”. Key words: grammar semantics runtime. The author’s ability is limited, in this article, will be in accordance with their own before learning to understand several aspects of the start.

I met

Introduction to the

  • React is an application for building user interfacesJAVASCRIPTLibrary.
  • React is primarily used to build uIs, and many people think of React as the V (view) of MVC.
  • React grew out of an internal Facebook project to build the Instagram site and opened source in May 2013.
  • React has high performance, very simple code logic, and more and more people are paying attention to and using it.
  • React Implements bidirectional data binding manually and uses state management in React.
  • The basic idea behind React is that components. Each component can also be considered a class that inherits from React.component.

Installation steps

To do a good job, you must sharpen your tools

  • Erection of scaffolding
npm install -g create-react-app
Copy the code
  • Initial project
create-react-app demo
Copy the code
  • Installing a plug-in
// if you are using vscode // this will help you quickly generate simple-react-snippets file structureCopy the code
  • The Google plug-in
React Developer Tools // Install it yourself //Copy the code

departure

JSX

JSX is a combination of Javascript and XML. React invented JSX, which makes it easy to create a virtual DOM using HTML syntax. When encountered with <, JSX interprets it as HTML and when encountered with {it interprets it as JavaScript.

class App extends Component{
    render(){
        return (
            <ul className="my-list">
                <li>I love React</li>
            </ul>)}}Copy the code

Simple to understand is to write HTML code in JS.

Data binding

React and Vue do not recommend direct manipulation of DOM elements. Instead, use data to drive changes in the interface. In React we define data in the constructor component.

// the js constructor, as any other function executes
constructor(props){
    super(props) // Call the parent constructor, fixed
    this.state={
        inputValue:' ' , // The value in input
        list: []/ / list}}Copy the code

Specific why is in this state, defined in [the React of official documentation] (https://react.docschina.org/) has details of state documents. Anyway, as a beginner, let’s just remember this is the definition.

<! -- Bind data -->
<input value={this.state.inputValue} /> 
Copy the code

The binding event

Once the data is defined, the next problem is that I need to manipulate the data, which requires binding events.

<input value={this.state.inputValue} onChange={this.inputChange} />
Copy the code

At this point you bind the onChange event to the input tag.

Some native methods or property names have been changed in JSX. Some are named after the hump, for example onchange=> onchange; Some have changed names, such as class=>className.

Pay special attention to

After you bind events in JSX, be sure to bind this as well

// If this is not manually bound, an error will be reported.
inputChange(e){
    console.log(this); // undefined
    this.state.inputValue=e.target.value; / / an error
}
Copy the code

There are two errors

  • This doesn’t point right, you need to bind again to point.
  • React uses the this.setState method to change values

The solution

/ / bind this
<input value={this.state.inputValue} onChange={this.inputChange.bind(this)} / >// Modify the data
inputChange(e){
    this.setState({
        inputValue:e.target.value
    })
}
// It is better not to change the value of state directly, but to define a temporary variable change to facilitate space-time backtracking
inputChange(e){
    let temp = e.target.value
    this.setState({
        inputValue:temp
    })
}
Copy the code

Conditions apply colours to a drawing

Vue conditional rendering expression v-if=” Boolean “; Angular conditional render expression *ngIf=” Boolean “; React uses the logical representation &&;

<ul> {this.state.list.map((item, key) => { return ( ! item.checked && ( <li key={key + item}> <input type="checkbox" checked={item.checked} onChange={this.checkBoxState.bind(this, key)} /> {item.title}---{' '} <button onClick={this.removeItem.bind(this, </button> </li>); })} </ul>Copy the code

True && expression is always evaluated to expression, and false && expression is always evaluated to false

The list of rendering

In JSX we use the map method for list rendering

<ul>
  {this.state.list.map((item, key) = > {
    return (
        <li key={key + item} >
           {item}
        </li>)); })} </ul>Copy the code

You also need to set the key for each entry in the loop.

A shaft

Father and son components

React and Vue are one-way data flows, which facilitates data management. It’s like a small company with a small number of people, you just have to shout. But big companies can’t issue orders by Shouting. The most effective way is to convey orders one way, layer by layer.

The parent component

// Content is the data passed
// funItem is the passing method
<ChildrenItem content={item} funItem={this.funItem.bind(this)} / >Copy the code

Child components

import React, { Component } from 'react'; //imrc(vscode plugin to generate code snippets quickly)
class ChildrenItem  extends Component { //cc
   constructor(props){
       super(props)
       // It is better to bind this to constructor to facilitate performance optimization
       this.handleClick=this.handleClick.bind(this)}render() { 
        return ( 
            <div onClick={this.handleClick}>{this.props.content}</div>
         );
    }
    handleClick(){
        // Do not modify the data from the parent component in the child component
        this.props.funItem()
    }
}

export default ChildrenItem;
Copy the code

Type checking

import React, { Component } from 'react';
import PropTypes from 'prop-types'
class ChildrenItem  extends Component { //cc
   constructor(props){... }render(){... }}// Type checks the value passed in
ChildrenItem.propTypes={
    content:PropTypes.string.isRequired,// Add isRequired
    funItem:PropTypes.func,
    name:PropTypes.string
}

// Set the default value
ChildrenItem.defaultProps = {
    name:'Joe'
}

export default ChildrenItem;
Copy the code

The life cycle

Lifecycle functions are functions that are automatically invoked and executed by the component at some point in time. React has four life cycles:

  • Initialization: Initialization phase
  • Mounting: Mounting phase
  • Updation: Renewal stage
  • Unmounting: Destruction stage

Constructor is not a lifecycle function; it is the basic syntax of ES6. But you need to think of it as a lifecycle function, which you can think of as the Initialization phase of React, defining the props and the state.

In our daily development tasks, we mainly operated the Mounting phase lifecycle function. With the generation of the entire virtual DOM, execute successively:

  • ComponentWillMount: Executed at the moment the component is about to be mounted to the page
  • Render: executes when the page state or props changes
  • ComponentDidMount: Executed when the component is mounted

The life cycle functions componentWillMount and componentDidMount are executed only once on a page refresh, while the Render function is executed whenever there are state and props changes

Data request

  • Install axios
npm install -S axios
Copy the code
  • Fast Mock
// Quickly generate test interface data
https://www.fastmock.site/
Copy the code
  • use
// componentDidMount is recommended because executing in render causes a lot of problems. Execute in componentWillMount, and when you use RN, you get collisions.
componentDidMount(){
    axios.post('https://www.fastmock.site/mock/ API you')
        .then((res) = >{console.log('Axios succeeded in getting data :'+JSON.stringify(res))  })
        .catch((error) = >{console.log('Axios fails to get data'+error)})
}
Copy the code

-save (-s) installs the module into the project directory and writes dependencies to the Dependencies node of the package file, which the project production environment needs. -save-dev (-d) installs the module into the project directory and writes dependencies to devDependencies in the package file, which is needed only in the development environment.

The break of dawn

ToDoList case

class ToDoList extends React.Component {
  constructor(props) {
    super(props);
    The first step in implementing two-way data binding is declared in state
    this.state = {
      value: ' '.list: [{title: 'eat'.checked: false },
        { title: 'sleep'.checked: false },
        { title: 'Beat the beans'.checked: false},]}; }handleChange(e) {
    this.setState({
      value: e.target.value,
    });
  }

  addData() {
    let title = this.state.value;
    // React does not modify state data directly. React does not modify state data directly. If you do this in the later performance optimization will be a lot of trouble
    // When modifying the data in state, we will define a local variable to change the data
    / / with... Adding data to an array is easier and more straightforward
    let tempList = [
      ...this.state.list,
      {
        title: title,
        checked: false,},];// Note that this.setState is an asynchronous method
    this.setState({
      list: tempList,
      value: ' '}); }checkBoxState(key) {
    let tempList = this.state.list; tempList[key].checked = ! tempList[key].checked;this.setState({
      list: tempList,
    });
  }

  removeItem(key) {
    let tempList = this.state.list;
    tempList.splice(key, 1);
    this.setState({
      list: tempList,
    });
  }

  // render function JSX
  // class -> className for -> htmlFor because class and for are javascript keywords
  // The React map loop replaces the for loop
  // Map must have a return and note that the use of a return can only return one line
  render() {
    return (
      // Fragment is a root node provided by React that does not render
      <Fragment>{/* Write comments in JSX, recommended */}<header className="title">TodoList:<input
            value={this.state.value}
            onChange={this.handleChange.bind(this)}
          />{' '}
          {'   '}
          {/* {this.state.value} */}
          <button onClick={this.addData.bind(this)}>add</button>
        </header>
        <h2>To do event</h2>
        <ul>{this.state.list.map((item, Return (// react key = key+item) // true && expression always evaluates to expression, And false && expression always evaluates to false // dangerouslySetInnerHTML={{__html: Item.title}} allows us to type HTML tags directly into text boxes. // This is recommended because JSX prevents injection attacks (CRO) parsers from converting code to strings! item.checked && (<li key={key + item} >
                  <input
                    type="checkbox"
                    checked={item.checked}
                    onChange={this.checkBoxState.bind(this, key)} / >
                  {item.title}---{'  '}
                  <button onClick={this.removeItem.bind(this, key)} >delete</button>
                </li>)); })}</ul>
        <h2>Completed event</h2>
        <ul>
          {this.state.list.map((item, key) => {
            return (
              item.checked && (
                <li key={key + item} >
                  <input
                    type="checkbox"
                    checked={item.checked}
                    onChange={this.checkBoxState.bind(this, key)} / >
                  {item.title}---{'  '}
                  <button onClick={this.removeItem.bind(this, key)} >delete</button>
                </li>)); })}</ul>
      </Fragment>); }}Copy the code

Write in the last

At this point, I believe you may have a basic understanding of React. Of course, the article may be wrong, please feel free to comment. It’s not easy to publish an article above the nuggets for the first time. Planned things, took the first step will have the next one footprint. It’s like the best time to plant a tree is 10 years ago, and the second best time to achieve it! Wish you like a knight, eyes blazing, indomitable!