This article is featured on Github github.com/Michael-lzg…

The characteristics of the React

  1. Using JSX syntax to create components for component-based development opens the door to functional UI programming
  2. High performance: efficient update of views through diff algorithm and virtual DOM

Why React

  1. The use of componentized development is in line with the trend of modern Web development
  2. Mature technology, perfect community, complete accessories, suitable for large Web projects (sound ecosystem)
  3. It is maintained by a dedicated team at Facebook with reliable technical support
  4. ReactNative – Learn once, write anywhere: Build mobile apps with React
  5. Simple to use, very high performance, support server-side rendering
  6. React is very popular. From a technical point of view, it can satisfy curiosity and improve technical level. From a professional perspective, it is good for job hunting and promotion, and it is good for participating in projects with high potential

There are two ways to create components

  1. Create (stateless component) from JS functions
  2. Create (stateful components) by class

JS function creation

  1. Function names must start with a capital letter. React uses this feature to determine if it is a component
  2. The function must have a return value, which can be a JSX object or NULL
  3. The JSX returned must have a root element
  4. The return value of the component is wrapped in () to avoid line breaks
function LearningList(props) {
  return (
    <div className="list">
      <h1>LearningList for {props.name}</h1>
      <ul>
        <li>Vue</li>
        <li>React</li>
        <li>Angular</li>
      </ul>
    </div>
  )
}

ReactDOM.render(<Welcome name="lzg" />.document.getElementById('app'))
Copy the code

The class to create

In ES6, a class is just a syntactic sugar, not a real class, essentially a constructor + stereotype implementation inheritance

class LearningList extends React.Component {
  constructor(props) {
    super(props)
  }
  // The component created by class must have the render method and return a React object or null
  render() {
    return (
      <div className="list">
        <h1>LearningList for {props.name}</h1>
        <ul>
          <li>Vue</li>
          <li>React</li>
          <li>Angular</li>
        </ul>
      </div>)}}Copy the code

JSX grammar

JSX syntax is a JavaScript syntax extension that can be easily used in React to describe the UI. For example, here is a JSX syntax

const element = <h1>Hello, world!</h1>
Copy the code

The above code is essentially equivalent to:

var element = React.createElement('h1'.null.'Hello, world! ')
Copy the code

JSX writing specification

  • The top layer of JSX can only have one root element, so we often wrap a div (or Fragment) around it.
  • Labels in JSX can be single or double labels. If it is a single label, it must end with />
  • JSX is wrapped in parentheses () to make it easy to read, and JSX can be written to a new line
  • Inside {}, you can write any code that conforms to the JS specification; If you write comments, they must be placed inside {}

Embedded expressions in JSX

In JSX syntax, you can place any valid JavaScript expression inside curly braces, which can be

  • Operational expression
  • Ternary operator
  • Execute a function
class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      firstName: 'kobe'.lastName: 'bryant'.age: 20,}}sayHello(name) {
    return 'Hello ' + name
  }

  render() {
    return (
      <div>
        <h2>{this.state.firstName + ' ' + this.state.lastName}</h2>
        <h2>{this.state.age >= 18 ? 'Adult' : 'minor '}</h2>
        <h2>{this.sayHello('lzg')}</h2>
      </div>)}}Copy the code

JSX conditional rendering

1. Choose between two components for rendering

class HelloMessage extends React.Component {
  render() {
    let userMessage
    if (this.props.loggedIn) {
      userMessage = (
       <h1>Welcome back!</h1>)}else {
      userMessage = (
        <h1>Please sign up.</h1>;) }return (
      <div>
         <h1>My Super React App</h1>       
         {userMessage}
      </div>)}}Copy the code

2, a component without rendering

function MessageList(props) {
  const unreadMessages = props.unreadMessages
  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 && <h2>You have {unreadMessages.length} unread messages.</h2>}
    </div>)}Copy the code

JSX list loop

In JSX syntax, loop rendering returns a collection using the traversal map() method of an array.

Traversal must have a unique index key to improve traversal efficiency. An element’s key should be a unique string that the element has in the list, and index should be used if necessary.

class Admin extends Component {
  constructor(props) {
    super(props)
    this.state = {
      menus: [{icon: require('.. /imag/home/[email protected]'), title: Menu '1' },
        { icon: require('.. /imag/home/[email protected]'), title: Menu '2' },
        { icon: require('.. /imag/home/[email protected]'), title: Menu '3' },
        { icon: require('.. /imag/home/[email protected]'), title: 'menu 4'},],}}renderList(value, index) {
    return (
      <li key={index}>
        <p>Zhang SAN</p>
        <p>18 years of age</p>
      </li>)}render() {
    return (
      <div>
        <ul>
          {[1, 2, 3, 4, 5].map((value, index) => {
            return this.renderList(value, index)
          })}
        </ul>
        <ul>
          {this.state.menus.map((value, index) => {
            return (
              <li key={index}>
                <img src={value.icon} width="30" />
                <div>{value.title}</div>
              </li>)})}</ul>
      </div>)}}Copy the code

Receiving data props

We want to pass values between components, so the props property does that. Each component of React can accept a props argument, which is an object that contains all the configuration you need for the component.

The characteristics of

  • React converts the properties passed to the component into an object and passes it to the props
  • Props is read-only and attributes cannot be added or modified to props
function Person(props) {
  return (
    <ul>
      <li>Name: {props. The name}</li>
      <li>Age: {props. Age}</li>
    </ul>
  )
}

ReactDOM.render(<Welcome name="lzg" age="18" />.document.getElementById('app'))
Copy the code

Component state

If you need to define custom properties for a component, you need to define state in the component’s constructor constructor

The characteristics of

  • Only components created through class have state
  • State is private and completely controlled by the component
  • Do not add data to state that is not needed in the render() method, which will affect render performance!
  • Do not call setState() in the Render () method to change the value of state

The difference between props and state

Props is the external interface of the component, and state is the internal interface of the component. The main differences are as follows: State is a set of UI components that are maintained internally, while props is a read-only property of the component. The props cannot be modified directly within the component, but only on the upper layer of the component.

Create the state

If you need to define custom properties for a component, define state in the component’s constructor constructor

class Mycom extends React.Component {
  constructor(props) {
    super(props)
    // Assign this.state to an object whose properties are the component's custom properties
    this.state = {
      name: 'lzg',}}}Copy the code

Change the state

You cannot directly modify the value of state, otherwise the data cannot drive the association. You need to use setState, and the setState method takes a parameter, which is an object, similar to the primitive setData of the applet.

// Wrong way
this.state.name = 'lzg'

// The correct way
this.setState({ name: 'lzg' })
Copy the code

It is always safer to use the second form of this.setstate () because the updated props and state are asynchronous. Here, we update the state based on these props.

// Wrong way
this.setState({
  total: this.state.total + this.props.count,
})

// The correct way
this.setState((state, props) = > {
  total: state.total + props.count
})
Copy the code

In addition, setState can take a second argument, which is a callback function

this.setState(
  {
    name: 'lzg',},() = > {
    console.log('State value changed successfully, now name value is' + this.state.name)
  }
)
Copy the code

Why don’t you just change state, setState? SetState does more than just change the value of this.state. The most important thing is that it triggers the React update mechanism, which diff and then updates the patch part to the real DOM.

event

1. Use bind to bind this when called

class Foo extends React.Component {
  handleClick() {
    this.setState({ name: 'lzg'})}render() {
    return <button onClick={this.handleClick.bind(this)}>Click me</button>}}Copy the code

2. Bind this in the constructor

class Foo extends React.Component {
  constuctor(props) {
    super(props)
    this.handleClick = this.handleClick.bind(this)}handleClick() {
    this.setState({ name: 'lzg'})}render() {
    return <button onClick={this.handleClick}>Click me</button>}}Copy the code

Bind this with the arrow function

class Foo extends React.Component {
  handleClick() {
    this.setState({ name: 'lzg'})}render() {
    return <button onClick={(e)= > this.handleClick(e)}>Click me</button>}}Copy the code

4. Public class Fields

class Foo extends React.Component {
  handleClick = () = > {
    this.setState({ name: 'lzg'})}render() {
    return <button onClick={this.handleClick}>Click me</button>}}Copy the code

The react style

  1. Write inline styles directly:
export const Footer = () = > {
  return <div style={{{color:'orange', fontSize:'12px'}} >All Rights Reserved 2019</div>
}
Copy the code
  1. Abstracted as object form
import React from 'react'

const footerStyle = {
  backgroundColor: 'green'.fontSize: '12px'.color: 'orange'.fontWeight: 'bold',}export const Footer = () = > {
  return <div style={footerStyle}>All Rights Reserved 2019</div>
}
Copy the code
  1. Using style sheets to define styles:
import '.. /css/comment.css'

export const Footer = () = > {
  return <div className="footer">All Rights Reserved 2019</div>
}
Copy the code

Life cycle function

The component lifecycle consists of three phases: Mounting, running and interacting, and Unmounting.

  1. Mounting Calls the following functions in sequence

    • Constructor ():ES6 class constructor(to initialize state or bind this)
    • GetInitialState (): Initializes state in ES5.
    • GetDefaultProps (): Initialization props in ES5. Use the defaultProps() method in ES6.
    • ComponentWillMount (): Called before the component is mounted. Perform this operation only once.
    • Render (): Render component, which must be implemented.
    • ComponentDidMount (): Called after the component is loaded. At this point, the actual DOM nodes have been generated. Perform this operation only once.
  2. Updating calls the following functions in turn

    • ComponentWillReceiveProps accept () component to trigger this method before the new props
    • ShouldComponentUpdate () determines whether to re-render the component based on the return value of this method, returns true to re-render, otherwise not
    • The componentWillUpdate() component will be updated
    • Render () rerenders the component, which is the same function as Render in the Mounting phase
    • The componentDidUpdate() component has been updated
  3. Unmounting

    • ComponentWillUnmount () unmounts components; Clear timer, clear DOM

PropTypes

As applications get larger over time, type checking is important. PropTypes provides type checking for components and good documentation for other developers. If react projects don’t use Typescript, it is recommended to add PropTypes to the component.

// The old way
class PropTypeOne extends React.Component {
  render() {
    return (
      <div>
        <div>{this.props.name}</div>
        <div>{this.props.email}</div>
      </div>
    )
  }
}

PropTypeOne.propTypes = {
  name: PropTypes.string,
  email: function (props, propName, componentName) {
    if (!/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/.test(props[propName])) {
      return new Error('components' + componentName + 'Attributes in' + propName + 'Does not fit mailbox format')}}}// New way of writing
class PropTypeTwo extends React.Component {
  static propTypes = {
    name: PropTypes.string,
  }
  render() {
    return (
      <div>
        <div>{this.props.name}</div>
      </div>)}}Copy the code

The JavaScript console displays a warning when an incorrect prop value type is passed in. For performance reasons, propTypes are checked only in development mode.

You can define the default value for props by configuring a specific defaultProps property:

class Greeting extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>}}// Specifies the default value of props:
Greeting.defaultProps = {
  name: 'Stranger',}// Render "Hello, Stranger" :
ReactDOM.render(<Greeting />.document.getElementById('app'))
Copy the code

Controlled and uncontrolled components

The controlled components

We often use forms to collect user input. Elements such as < SELECT > < texteArea > are bound to a change event. When the state of the form changes, the onChange event is triggered to update the state of the component. This type of component is called a controlled component in React. In a controlled component, the rendered state of the component corresponds to its value or Checked property. React eliminates the local state of the component in this way and makes the overall state controllable. React officials also recommend using controlled forms components.

import React, { Component } from 'react'
export default class MyInput extends Component {
  handleContentChange = (e) = > {
    this.setState({
      content: e.target.value,
    })
  }
  render() {
    return (
      <div>
        <input type="text" value={this.state.value} onChange={this.handleContentChange} />
      </div>)}}Copy the code

The process of updating state for controlled components:

  • You can set the default value of the form in the initial state
  • The onChange event handler is called every time the value of the form changes
  • The event handler gets the changed state from the event object E and updates the component’s state
  • Once the state is updated with the setState method, the view is rerendered and the form component is updated

React data flows in a single direction. From the example, we can see that the form data comes from the component’s state and is passed in through props. This is also known as one-way data binding. We then write the new data back to state via the onChange event handler, completing two-way data binding.

Uncontrolled component

A form component is an uncontrolled component if it has no value props (radio and check buttons correspond to Checked props). In uncontrolled components, we can use a ref to get form values from the DOM. Instead of writing an event handler for each status update.

class NameForm extends React.Component {
  constructor(props) {
    super(props)
    this.handleSubmit = this.handleSubmit.bind(this)}handleSubmit(event) {
    alert('A name was submitted: ' + this.input.value)
    event.preventDefault()
  }

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

ref

React supports a very special attribute called Ref that you can use to bind to any component of the render() output.

String usage

Refs [‘inputRef’]

<input ref="inputRef" />
Copy the code

Ref acts as the callback function

class AutoFocusTextInput extends Component {
  componentDidMount(){
    this.textInput.focus();
  }
  render(){
    return (
      <Input ref={(input)= > { this.textInput = input }}>
    )
  }
}
Copy the code

The parent component’s REF callback function can use the child component’s DOM.

function CustomTextInput(props) {
  return (
    <div>
      <input ref={props.inputRef} />
    </div>)}class Parent extends React.Component {
  render() {
    return <CustomTextInput inputRef={(el)= > (this.inputElement = el)} />}}Copy the code

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

class Child extends React.Component {
  constructor(props) {
    super(props)
    this.myRef = React.createRef()
  }
  componentDidMount() {
    console.log(this.myRef.current)
  }
  render() {
    return <input ref={this.myRef} />}}Copy the code

react-router

React-router-dom is a routing library in your application. The React library does not provide routing functions. Install the React -router-dom separately.

React-router-dom provides two routers BrowserRouter and HashRoauter. The former is based on the PATHName segment of the URL, while the latter is based on the hash segment.

Basic use:

npm install react-router-dom --save
Copy the code
import { BrowserRouter, Route, Link, Redirect } from 'react-router-dom'

class MyRouter extends React.Component {
  render() {
    return (
      <BrowserRouter>
        <Link to="/">router1</Link>
        &nbsp;&nbsp;
        <Link to="/router2">router2</Link>
        &nbsp;&nbsp;
        <Link to="/router3">router3</Link>
        &nbsp;&nbsp;
        <hr />
        <Redirect exact from="/" to="/router1" />
        <Route path="/router1" component={router1}></Route>
        <Route path="/router2" component={router2}></Route>
        <Route path="/router3" component={router3}></Route>
      </BrowserRouter>)}}Copy the code

Routing hop

1. Jump with the Link tag

import { BrowserRouter, Route, Link, Redirect } from 'react-router-dom'

class MyRouter extends React.Component {
  render() {
    return (
      <BrowserRouter>
        <Link to="/">router1</Link>
        &nbsp;&nbsp;
        <Link to="/router2">router2</Link>
        &nbsp;&nbsp;
        <Link to="/router3">router3</Link>
        &nbsp;&nbsp;
        <hr />
        <Redirect exact from="/" to="/router1" />
        <Route path="/router1" component={router1}></Route>
        <Route path="/router2" component={router2}></Route>
        <Route path="/router3" component={router3}></Route>
      </BrowserRouter>)}}Copy the code

2. Programmatic navigation

  • The routing component can get the history directly from this.props. History
  • Non-routed components cannot get history directly and need to work with withRouter
this.props.history.push(url)

this.props.history.go(-1)
Copy the code

Routing and the cords

1.params

<Route path='/path/:name' component={Path}/>
<link to="/path/123">xxx</Link>

this.props.history.push({pathname:"/path/" + name});
/ / read parameters: this. Props. Match. Params. Name
Copy the code

2.query

<Route path='/query' component={Query}/>
<Link to={{ pathname : '/query',query : { name : 'sunny' }}}></Link>

this.props.history.push({pathname:"/query".query: { name : 'sunny' }});
/ / read parameters: this. Props. The location, query. Name
Copy the code

3.state

<Route path='/sort ' component={Sort}/>
<Link to={{ pathname : '/sort',state : { name : 'sunny' }}}></Link>

this.props.history.push({pathname:"/sort ".state : { name : 'sunny' }});
/ / read parameters: this. Props. The location, query. The state
Copy the code

4.search

<Route path='/web/search ' component={Search}/>
<link to="web/search? id=12121212">xxx</Link>

this.props.history.push({pathname:`/web/search? id${row.id}`});
/ / read parameters: this. Props. The location. The search
Copy the code

Routing guard

The Route Component can receive a Component that will be rendered when the path is matched. We can also do something after a path match, similar to the route guard in Vue.

The Route Component is used again, but instead of passing data through the Component, the render property is used.

import { Route } from 'react-router-dom'

function Custom() {
  return (
    <Route
      path="/index"
      Render={()= >{//isLogin Checks whether the user is logged in. If the user is logged in to the render page but not logged in to the render page if (isLogin) {return<Index></Index>
        } else {
          return <Login></Login>
        }
      }}
    />)}Copy the code

withRouter

The withRouter of the high-order component wraps a component inside the Route. Then the three objects of the React – Router, history, location, and match, are placed in the props property of the component.

By default, this. Props must have route parameters if the component is routing-matched. To use programmatic navigation, execute this.props. However, not all components are directly connected to routing (routing to this component), so when those components need routing parameters, you can use the withRouter to pass routing parameters to the component, so you can use this.props.

import React,{Component} from 'react'
import {Switch,Route,NavLink,Redirect,withRouter} from 'react-router-dom' / / introduce withRouter
import One from './One'
import NotFound from './NotFound'
class App extends Component{
  // Get this. Props, which contains (history, match, location)
  console.log(this.props);  // output {match: {... }, location: {... }, history: {... }, etc.}
  render(){
    return (<div className='app'>
      <NavLink to='/one/users'>List of users</NavLink>
      <NavLink to='/one/companies'>The company list</NavLink>
      <Switch>
         <Route path='/one/:type? ' component={One} />
         <Redirect from='/' to='/one' exact />
         <Route component={NotFound} />
      </Switch>
    </div>)}}export default withRouter(App);  // Perform WithRouter
Copy the code

Recommend the article

Talk about data state management and implementing a simplified version of Vuex
Summary of 18 Webpack plugins, there’s always something you want!
Build a VuE-CLI4 + WebPack mobile framework (out of the box)
Build from scratch to optimize a vue-CLI-like scaffolding
Encapsulate a TOAST and Dialog component and publish it to NPM
Build a WebPack project from scratch
Summary of several webpack optimization methods
Summary of advanced application of VUE knowledge system
Summarize the practical skills of vUE knowledge system
Summarize the basic introduction to vUE knowledge system
Summary of mobile H5 development tips.