React project development basic use

Install the Node environment before developing the React project

  1. Search node.js for the official website
  2. Install the latest stable version of Node (NPM is integrated with Node.js package management tool)
  3. After the installation is complete, enter a value on the terminalnode -v.npm -vIf the output version information is available, it can be used normally. (If the command cannot be found, search and configure the global PATH by yourself.)

Create-react-app (commonly known as CRA) is the official scaffolding for building React projects.

(CRA does not require installation or configuration of tools such as Webpack or Babel. They are pre-configured and hidden, so you can focus on code that needs customization and modification. You can expose the webpack configuration file using the eject command. Run NPM I -g create-react-app create-react-app [project name] the project is created in the current directory CD [project name] Go to the root directory NPM run start Run the command to start the CRA document portal The usage of NPM is not explained much, so do your own research. Here is a sandbox environment for online development: codesandbox.io/s


JSX introduction

React applications usually write programs using JSX syntax (not mandatory), which is a JavaScript syntax extension somewhat similar to HTML/XML.

By default, the React DOM escapes all input before rendering it. It ensures that you never inject content into your application that you didn’t explicitly write. All content is converted to a string before rendering. This effectively protects against XSS (cross-site scripting) attacks, so it’s safe to eat. For XSS, see the following example:

Suppose we have a comment function for an e-commerce system. User A submits A comment [Logistics is fast! Go to the server, then user B visits the site, then user B sees A’s comment [Logistics is fast!] . User C submits a comment [], and then user B visits the website. This script is executed directly in B’s browser, and user C’s script can manipulate B’s cookie arbitrarily. With cookies, malicious user C can forge B’s login information, and the negative impact on security is self-evident.


This is a JSX example

const ReactNode = () = > (
  <div
    className="my-class"
    //className={`my-class'} can also be usedJavaScriptexpressionstyle={{ color: `red`,marginLeft: 8}} // The inline style is written in object style, the first {} annotation here isJavaScriptExpression, and the second parenthesis is an objectonClick={(event)= >{ console.log(event.currentTarget.tagName); }} > {window.innerheight} {/* This is a comment... * /}</div>
)
Copy the code

This is not a string, it’s not HTML, it’s JSX syntax.

Notes for writing JSX:

  1. The React component must start with a uppercase letter. The React component name that starts with a lowercase letter is considered a built-in HTML component.
  2. JSX used{}The identifier indicates here{}The code in is a JavsScript expression.
  3. Attribute names follow the hump naming convention.
  4. Use className and htmlFor instead of class and for.
  5. Components can be nested from one another.
  6. In JSX syntax you can only use evaluated expressions, not statements, so you cannot use themif... else....for.
  7. You can use a ternary expression? : .<span className={window? ` trueClassName ` : ` falseClassName `} > a tag < / span >.
  8. Instead of writing App() to reactdom.render, App is a function component that can be used as a tag.<App/>), the App function is automatically called.
  9. Functions can be called directly from {}.
const GetComponent = (props) = > {
  if (props) {
    return <div>You passed props</div>;
  } else {
    return <div>There is no props</div>; }};/ / JSX syntax
<>
{GetComponent()}
</>
// If you write 
      , React will process the function, and the function will be assigned {} for props. In this example, the function will be true.
Copy the code
  1. Use short circuiting operators && | |
let visibled = false

{visibled && <div>Welcome</div>} {! visibled ||<div>Welcome to | | coming</div>}
Copy the code
  1. There can only be one top-level tag, and empty tags can be used if you do not want to output the actual tag<React.Fragment></React.Fragment>Or abbreviations<></>Wrapped as the outermost element.
  2. Boolean types, Null, and Undefined are ignored. False, null, undefined, and true are valid child elements. But they don’t get rendered<div>{null}</div>The UI is rendered blank.
  3. JSX is optional (but it does not write React syntax directly and is much less readable and efficient)

Hello! < / a > the following is corresponding to not use JSX writing: the React. The createElement method (‘ a ‘, {href: ‘https://facebook.github.io/react/’}, ‘Hello! ‘)

  1. Inline styles accept numeric JavaScript object values that automatically add the default unit (PX). If you want to use em or any other unit of REM, you need to use strings.{top:2,left:`${2}em`,right:'10rem',bottom:"11px"}
  2. DangerouslySetInnerHTML is an alternative to the innerHTML provided by React to the browser DOM. In general, setting up HTML directly with code is risky because it is easy to unintentionally expose users to cross-site scripting (XSS) attacks. Therefore, you can set HTML directly in React, but when you want to set dangerouslySetInnerHTML, you need to pass it an object containing key __html to warn you. Such as:
function MyComponent() {
  return <div dangerouslySetInnerHTML={{__html: '<p>hi</p>'}} / >
}
Copy the code
  1. In JSX, attribute names with no specific value are set to true. For example, the first input tag, disabled, is set to the same value as the following input tag:
<input type="button" disabled />;
<input type="button" disabled={true} />
Copy the code
  1. Custom properties.

If you want to use custom attributes, you can use data-.

<MyComponent data-attr="test" />
Copy the code
  1. Expand the syntax. Used in ES6.You can iterate over all the corresponding values of the object to set the attributes, but be aware that the attributes set later will overwrite the previous same attributes.
var props = {
  style: {"width":"20px"},
  className: "main".value: "yo",}// After value, the value attribute of the props object is overridden<div {... props} value="str" />
Copy the code
  1. JSX cannot render objects directly or an error will be reported. Do want to output objects can passJSON.stringify()Convert to string output.
  2. JSX allows you to insert arrays into templates that automatically expand all members, provided that the array item is not a normal JavaScript object, but can be a React element.
(This is just a list of things I do on a daily basis. Check React JSX for more.)

The React elements

JSX scripts are eventually compiled into the React. CreateElement form via Babel (see note 13), which is why the React component needs to import React from ‘React’ even though React is not explicitly called in the code. The reac. createElement return value ReactElement can represent a div, but ReactElement is not a real DIV (DOM object), so ReactElement is usually called a virtual DOM element. React compares two virtual DOM’s to find the difference, locally updates the view, and finds a different algorithm called the DOM Diff algorithm.


Function components and class components. The class component is mainly introduced here

Stateless components can be used as pure functional components (the new Hook API in Act 16.8 emulates the features of class components to manage their own state and life cycle), which is not covered here.

A function component is a pure function
function MyFnComponent(props){
    return (<div>{props.name}</div>)}// If the function component is called with a tag and no props is passed, the props is empty; The use of functions without passing props is undefined.
Copy the code

Stateful components are written in ES6 class notation

Here is a basic class component
// Class is the syntax sugar of Prototype, __proto__, inheritance, etc
// The class component needs to inherit from react.component
(extends, constructor, super)
export default class MyClassComponent extends React.Component {
  constructor(props) {
    super(props) // Call the constructor of the parent class
    this.state = {
      data: [1.2.3.4] // Initializes its own manageable state}}This is a new ES6 syntax that would automatically bind this to it
  addOne = () = > {
    let { data } = this.state
    this.setState({ data: [...data, data.length + 1]})// Destruct the assignment
    // this.setState({data: data.concat([data.length+1])}
  }
  
  render() {
    let { data } = this.state;
    return (
      <>
        <div>{data}</div>{/* Array can render valid items directly */}<button onClick={this.addOne}>Click my array plus one item</button>
      </>)}}Copy the code

Props External data

When the React element is a user-defined component, it converts attributes and children received by JSX into a single object passed to the component, which is called “props.”

Initialize props, external data supplied by the parent component

class Child extends React.Component {
    constructor(props) {
        super(props) // After passing props to super, this.props is the address of the external data object
    }
    render(){}}Copy the code

Read the props

const onClick = () = >{ console.log('u click me') }
<Child name='JackMa' onClick={onClick}>
    <div>i am children</div>
</Child>
/ / the parent component
//----------------

class Child extends React.Component {
    constructor(props) {
        super(props);
    }
    render(){
        return (
        <div onClick={this.props.onClick}>U click me {this.props. Name} // output JackMa<div>
                {this.props.children} //<div>i am children</div>//this.props. Children contains the content between the start and end tags of the component</div>
        </div>)}}Copy the code
Do not attempt to modify the props. Keep the props read-only. External data must be updated externally. If it is necessary to modify the props, pass in the method as props for the child component.

State && setState Internal data

Initialize state, and external data is provided by the parent component

class Child extends React.Component {
    constructor(props) {
        super(props) 
        this.state = {
            userInfo : {
                name : 'JackMa', the age:18, gold:9999,}}}render(){}}// Use es6
class Child extends React.Component {
    state = { // As written in constructor, state is eventually tied to the instance
        userInfo : {
            name : 'JackMa', the age:18, gold:9999,}}render(){}}Copy the code

Write state, using setState setState can be written in two ways. Fn is the optional callback function that will be executed after setState has been merged and rerendered. Multiple consecutive calls to setState will eventually be merged into one

  1. setState({key:value},fn)
this.setState({name:'Tony'},() = >{console.log('i execute')})
Copy the code
  1. setState((state,props)=>newState,fn), the state and PORps parameters received by the updater function are up to date
this.setState(
      (state, props) = > {name:'Tony'}, 
      () = > {
        console.log("i execute"); })Copy the code
SetState is asynchronous. This. State is not the latest state and will be updated after the current code is run to trigger UI update. Use the callback function for componentDidUpdate or setState to read the updated state, both of which are guaranteed to fire after the update is applied.
SetState automatically merges the new state with the old state

The life cycle of a class component

constructor()

Function:

  1. Initialize the props
  2. State is initialized, but this.setstate cannot be called
  3. Bind this (band)
class Child extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
        data : [1.2.3]}this.testFn = this.testFn.bind(this)}testFn(){
      console.log(this)}render(){
      return (
        <button onClick={this.testFn}>click</dutton>)}}Copy the code

When a subclass does not explicitly declare constructor methods, constructor is automatically filled in during execution

class Child extends Father {}/ / is equivalent to
class Child extends Father {
  constructor(. args) {
    super(...args);
  }
}
Copy the code

Remember the unspoken rule that constructor must write super() or else return an error.

shouldComponentUpdate()

Function:

  1. The component executes each time it executes Redner
  2. The function returns false to block UI updates
  3. The function returns true to allow UI updates
  4. Manually check whether components need to be updated and flexibly set the return value based on the actual service logic to avoid unnecessary UI updates
  5. React.PureComponent has this built in as an alternative to react.component.react.ponent
// We can compare newState with this.state, and return true if there are differences
shouldComponentUpdate(newProps,newState){ // The function accepts two values, new props and new state
    if(newState.key === this.state.key){
        return false
    }else{
        return true}}Copy the code

render()

Effect: Render view

render(){
    return (<div>halo,world!</div>)}Copy the code

componentDidMount()

Function:

  1. Executes code that depends on the DOM after the component is mounted (inserted into the DOM tree)
  2. You can get information about DOM elements
  3. The official recommendation is to make an Ajax request here
  4. This hook is executed only when the component is first rendered
componentDidMount(){
    console.log('I'm only going to do it once')
    // This is pseudocode
    handelDom() // Manipulate DOM elements
    ajax() // Initiate an Ajax request
}
Copy the code

componentDidUpdate()

Function:

  1. Execute code after view update
  2. This hook is not executed when the component is first mounted
  3. Ajax requests can also be made here
  4. Do not call this.setState directly, otherwise it will go into an infinite loop and must be wrapped in a condition statement.
  5. If shouldComponentUpdate() returns false, componentDidUpdate() is not called.
Acceptable parameters: see the official documentation
componentDidUpdate(prevProps, prevState){
    // This is pseudocode
    judgeProps() // Get new props
    judgeState() // Get the new state
    handelDom() // Manipulate DOM elements
    ajax() // Initiate an Ajax request
}
Copy the code

componentWillUnmount()

Function:

  1. The code is executed before the component is removed from the page and destroyed
  2. Example: After the component is mounted (listen for events, initiate requests, add timers), cancel on this hook (listen, timer, request)

ForceUpdate () is not used for personal use (and is not officially recommended)

Hook execution order

Controlled components && Controlled components

The controlled components

React’s own state, state, becomes the “unique data source”. The React component that renders the form also controls what happens to the form during user input. The form input elements that React controls their values in this way are called “controlled components.”

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ' '}
  }

  handleChange = (event) = >{
    this.setState({value: event.target.value});
  }

  handleSubmit = (event) = > {
    console.log(this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>Name:<input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>); }}Copy the code

Uncontrolled component

The uncontrolled component form data is handled by a DOM node, which is referenced by ref in the React program

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.input = React.createRef()
    // After React 16.3, use this method to create refs. Assign it to a variable, mount it to a DOM node or component by ref, and the ref's current property gets an instance of the DOM node or component
  }

  handleSubmit = (event) = > {
    console.log(this.input.current.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" ref={this.input} />
          //<input type="text" ref={ref= >//ref="input" is a string binding, and this.refs.[string] is also a Dom reference</label>
        <input type="submit" value="Submit" />
      </form>); }}Copy the code

CSS scheme

React’s CSS scheme, the mainstream has in-line styles, Styled styles, CSS Modules, Styled Components. It is not recommended to use solutions that introduce CSS files (except for resetting and custom global styles), because styles are global and there may be style conflicts. If you have two CSS files with the same style name, one of them will be overwritten. Styled Components are recommended, similar to most of the syntax of Sass and less, such as nesting and inheritance.

Introduction to String Templates

// First install NPM I Styled - Components via NPMCopy the code

Some simple usage introduction

// Need to be introduced first
import styled from 'styled-components'

// Creates a TestDiv style component that will render a styled div tag
// The first letter of the component name should still be capitalized, followed by the string template
const TestDiv = styled.div` background:red; < span style = "box-sizing: border-box! Important; } color:${props => props.color}; // Props can be used to obtain the parent parameter, and then perform an assignment. Background:${props => props.primary ? "palevioletred" : "white"};
    font-size: ${props => props.fontSize ? `${props.fontSize}px` : "10px"};
`

// Inherits the styles of TestDiv and adds additional styles to them
const ChildComponent = styled(TestDiv)` color: red; `
Copy the code

See the Styled – Components documentation for more uses


Introducing images in React projects, import does not follow the same modular specification as require

Using the import

import Img from './images/1.png'
<img src={Img} alt=' ' />
Copy the code

Using the require

<img src={require("./images/1.png")} alt="">
Copy the code

Inline style

style={{background: `url(The ${require("./images/1.png")}) `}}

import bgImg from './images/1.png'
style={{background: {bgImg}}}
Copy the code

Send network requests in the React project

Give some examples of common solutions

  1. jQuery $.ajax
  2. Fetch API
  3. Axios
  4. Request
  5. SuperAgent
Axios is recommended, with perfect API and powerful functions

Axios Chinese document


Routing scheme for the React project

Use the react-router-dom official documentation


React main UI library recommendation

Using third-party UI libraries can save development time and ensure standardization and uniqueness. Whether you’re writing your own component or using a third-party UI library, you can’t avoid bugs. Try to use a proven library (see the project’s Star count on Github).

  1. Ant Design
  2. react-bootstrp
  3. MATERIAL-UI
  4. React Suite
  5. Elemental UI