“This is the 12th day of my participation in the August More Text Challenge. For details, see: August More Text Challenge.”

I strive to write every step can be practical, hope to follow the writing practice.

Project run

First install the scaffolding and use it to create a new project

NPM I create-react-app-g # Create project create-react-app react-demoCopy the code

Open the project using VSCode. The entire project directory looks like this:

React-demo ├── readme.md ├── node_modules ├─ package.json ├─ public ├─ SRC ├─ yarn.lockCopy the code

The entry point for the entire project is SRC /index.js, which implements the function of calling the reactdom.render method to render the view.

Let’s take a look at the reactdom. render method, which is signed as follows:

ReactDOM.render(element,container[,callback])
Copy the code

This method renders the React element into the provided Container and returns a reference to that element. Click on the official documentation to see the API

Official document render()

Now what is the React element?

The React element is actually the result of a JSX expression (expression 1+2 results in 3, which can be interpreted as the return value).

What is the JSX

JSX is a syntactic extension of JS that allows you to write HTML-like structures in JS. Here’s an example:

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

The element constant above is a React element

Modify the contents of the index.js file as follows

const element=<h1>hello,world</h1>
ReactDOM.render(
  element,
  document.getElementById('root'));Copy the code

Refresh the page and see that the browser page renders the Element’s content. A) App B) element Here the App is called a component.

Before studying components, familiarize yourself with the syntax of JSX

Expressions are allowed in JSX and are enclosed in {} brackets


const name="Jack"
const Welcom=<h1>Hi,{name}</h1>
// Expressions can be variables, function calls, numeric expressions (a+b), etc
const getTime=() = >{}
const Clock=<h1><span>Now is:</span> <b>getTime()</b></h1>

// The difference from Html
// The class in HTML is className in JSX
const blog=<section className="blog"></section>

/ / binding style
const btnStyle={padding:'5px 20px'}
const myBtn=<button style={btnStyle}></button>
// or just write them together
const myBtn1=<button style={{padding:'5px 20px'}} ></button>

// Bind the event
const clickHandle=() = >{}
const myBtn2=<button onClick={(e)= >{clickHandle(e)}}></button>
Copy the code

Having explained the basic use of JSX syntax, let’s take a look at the components in React.

Components in React

There are two components in React. One is a functional component, similar to the App above. One is the class component.

Before React Hooks came along, functional components couldn’t have their own internal state. They could only pass props through their parent component and then display their content, which is one of the programming methods recommended by React. Modify app.js code as follows to experience the writing of functional components:

// The parent of the functional component passes the props as the function argument
function Logo({src}){/ / receive props
    return  <img src={src} className="App-logo" alt="logo" />
}

// Call the Logo component
function App() {
  return (
    <div className="App">
      <header className="App-header">
        <Logo src={logo}></Logo> //传递props
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
      </header>
    </div>
  );
}
Copy the code

Another component is class component. If you use it, you need to inherit React.Com component first. The learning of class component can correspond to vUE component, and everything that vUE can achieve must be implemented in React

Suppose we want to implement a component that displays the current time, and the color that the component displays is controlled by the parent component

Vue2 is implemented as follows:

<template>
    <section :style="{ color: color }">Current time: {{curTime}}</section>
</template>

<script>
export default {
    name: 'clock'.props: {
        color: {
            type: String.default: '# 333',}},data() {
        return {
            curTime: 0.timer: 0,}},mounted() {
        this.timer = setInterval(() = > {
            console.log('hahah')
            this.curTime = new Date()},1000)},beforeDestroy() {
        clearInterval(this.timer)
    },
}
</script>
Copy the code

The React implementation is as follows: You can copy the code into app.js and run it to see what happens

Class Clock extends React.Com {constructor(props) {super(props) this.state = {// equivalent to vue data curTime: }} componentDidMount() {// Mounted const timer = mounted () => {this.setstate ({curTime: 0)}} componentDidMount() {// mounted const timer = mounted () => {this.setstate ({curTime: 0); new Date().toString() }) }, 1000) this.setState({ timer: BeforeDestroy clearInterval(this.state.timer)}} componentWillUnmount() {// beforeDestroy clearInterval(this.state.timer)} render() {return () <section style={{ color: {this.state.curtime} </section> </Clock> </Clock>Copy the code

The instance-list query component compares the vuE2 and React components

Here’s a more complicated example to familiarize yourself with react Class Component

Write an example of a list query

The overall business process is:

  1. The QueryList component gets the data, passes props to the List, and the List traverses the data rendering view
  2. QueryList gets the data, filters it based on the searchKey, and passes props to the render view List

There are three components

  • QueryList
  • List
  • Query

Implement the List component first

Vue implementation

< span style=" max-width: 100%; clear: both; min-height: 1em; 10px" v-for="item in list" :key="item.name"> ID: {{item. ID}} Name: {{item.name}} Age: {{ item.age }} </div> </section> </template> <script> export default { name: 'List', props: { list: { type: Array, default: () => [], }, }, computed: { noData() { return this.list.length == 0 }, }, } </script> <style lang="less" scoped></style>Copy the code

Using React

import React from 'react' class List extends React.Component{ constructor(props){ super(props) console.log() } get noData(){//computed return this.props.list.length===0 } getList(){ return this.props.list.map(item=>{ return <div Key ={item.name}> ID: {item.id} name: {item.name} {item.age}</div>})} render(){const list=this.getList() const dom= this.nodata? return <div>{dom} </div> } } export default ListCopy the code

Here are some of the differences.

  • Props need to be declared before using vue, but can be used directly in react

  • Vue lists are rendered using the V-for directive, and React is rendered using the MAP method of JS arrays that returns JSX

  • There are computed properties in vue, not in React, but you can do it with getters like get noData(){}

  • There is v-if in vue, not in React, but it can be implemented in other ways, such as the termexpression const dom= this.nodata?

    {list}

Implement the Query component: vUE implementation

<template>
    <section>
        <input
            placeholder="Enter the id"
            style="padding: 12px; font-size: 40px"
            v-model="id"
            @input="handleChange"
        />
    </section>
</template>

<script>
export default {
    name: 'Query'.data() {
        return {
            id: ' ',}},methods: {
        handleChange() {
            // Send data to the parent component
            this.$emit('on-change'.this.id)
        },
    },
}
</script>

<style lang="less" scoped></style>
Copy the code

The react to realize

import React from 'react'
class Query extends React.Component{
    constructor(props){
        super(props)
    }
    testThis(){
        console.log(this)
    }
    onChange=(e) = >{// Prevent this from being lost
        // Send a message to the parent component
        this.props.onQuery(e.target.value)
    }
    render(){
        return <input style={{padding:'10px',fontSize:'20px'}} placeholder="Enter the id" onChange={this.onChange}  />}}export default Query
Copy the code

The differences are as follows:

  • $emit(). React calls the parent method (this.props. Callback) directly

  • The element binding event in VUE uses @event name, and the element binding event in React uses ON event name. In addition, it should be noted that the element binding event in React needs to pay attention to the loss of this, and pay attention to the definition of onChange method above

QueryList components

Vue implementation

<template>
    <section>
        <! -- Query list Component query box list -->
        <query @on-change="handleChange"></query>
        <list :list="list"></list>
    </section>
</template>

<script>
import query from './query'
import list from './list'
import axios from 'axios'

export default {
    name: 'query-list'.components: {
        query,
        list,
    },
    data() {
        return {
            list: [].}},methods: {
        async getList(id = -1) {
            const res = await axios.request({
                method: 'get'.url: '< http://111.229.14.189/gk-api/util/list >'.params: {
                    id: id,
                },
            })
            this.list = res.data
        },
        handleChange(id) {
            this.getList(id)
        },
    },
    created() {
        this.getList()
    },
}
</script>
Copy the code

The react to realize

import React from 'react';
import Query from './Query.js'
import List from './List.js'
import axios from 'axios'

class QueryList extends React.Component{
  constructor(props){
      super(props)
      this.state={ 
        list: []}}componentDidMount(){
    this.getList()
  }
  async getList(id=-1){
    const res=await axios.request({
      method:'get'.url:'< http://111.229.14.189/gk-api/util/list >'.params: {id:id
      }
    })
    this.setState({list:res.data})
  }
  handleQuery=(value) = >{
   this.getList(value)
  }
  render(){
    return (
      <div className="query-list" >
        <Query onQuery={this.handleQuery}></Query>
        <List list={this.state.list}></List>
      </div>); }}export default QueryList;
Copy the code

The differences are as follows:

  • Vue calls the interface in created or Mounted, react calls the interface in componentDidMount

  • The state of the component itself in vue is defined in data, which can be modified directly by this.list= XXX; This.setstate ({list: XXX}) {list: XXX}}

In general, people who have written VUE will find react Class Component a little tedious to write. Thanks to the use of hooks grammar in React, you can get rid of a lot of redundancies. Hooks will be introduced in the next article.

The code address

  • Vue code
  • The react of the code