Home > Web Front-end > JS Tutorial > body text

How does React work? The whole process of making a react case from scratch

寻∝梦
Release: 2018-09-11 15:29:32
Original
1733 people have browsed it

This article mainly talks about the detailed steps of making a react case from scratch. Let’s take a look at the specific content of the article

Example description

Next we will learn the content of React in detail through a simple case
How does React work? The whole process of making a react case from scratch

As shown in the picture above, there are two buttons. Click the plus button and the number will increase by one. Click the minus button and the number will decrease by one.

Code structure

Usecreate-react-appCreate a project and reduce the code structure to the simplest mode

How does React work? The whole process of making a react case from scratch

Modify index.js

The code in

index.js is very simple. Just introduce the App component and perform rendering.

import React from &#39;react&#39;;import ReactDOM from &#39;react-dom&#39;;import App from &#39;./components/App&#39;ReactDOM.render(<App/>, document.getElementById(&#39;root&#39;));
Copy after login

The basic content of the component

App The content in .js is the logic we want to actually implement. We will use ES6 to create a React component. The steps are as follows

  1. Introduce react

import React from &#39;react&#39;
Copy after login

2. Create a component, let the component inherit React.Component, and implement the render function

class App extends React.Component{
    render(){        return (
            <p>
            </p>
        )
    }
}
Copy after login

3. Specify the default output for the component

export default App
Copy after login

The complete code is as follows:

import React from &#39;react&#39;;class App extends React.Component{
    render(){        return (
            <p>
            </p>
        )
    }
}
export default App;
Copy after login
  • React.Component is one of react Abstract base class, it is meaningless to reference it alone. We usually use it to implement subclasses. When implementing subclasses, we must implement its render function

  • The render function is used to return components The content, and the rendering process is completed by the react framework. There can only be one top-level tag element in return()

  • export defaultSpecifies the default module output by the current component

Function implementation

The content in the example can be divided into four parts

1. Plus button
2.Minus button
3. Simple text
4. The numbers that change when you click the button with the mouse

The buttons and text are very simple, but the numbers need to be changed by clicking the mouse. If we have not learned any front-end framework, we have to use the document object , get the content of the page, convert it into numbers, calculate the numbers, and then write the calculation results to the page. When using react to implement it, we need to know that the core goal of react is componentization, and the transformable content in the component is called state (If you want to see more, go to the PHP Chinese websiteReact Reference Manual column to learn)

There are two types of data sources in components, internal declarationandexternal transmission Enter , and use state and prop to distinguish and represent them respectively. In the es6 component, you can receive the prop from the outside and declare the state data used internally through the constructor constructor. In the example of this article, we need to use a number that changes continuously after the mouse clicks

constructor(props){
    super(props);
    this.state = {
        count:0
    }}
Copy after login

We have declared the internal state and received the external incoming array. Next, I implement the display content of the page, that is Realize the content in the render function

    render(){
        return (            <p>
                <button>+</button>
                <button>+</button>
                <span>当前点击次数</span>
                <span>{this.state.count}</span>
            </p>
        )
    }
Copy after login

How does React work? The whole process of making a react case from scratch

The rendering effect is shown in Figure 1-3

Content beautification

From the page effect , the various elements are close together, which does not look good. We use simple css to beautify them. The goals to be achieved are:
- Increase the top margin and left margin of the entire content
- Buttons, text, and numbers interact with each other There is a certain spacing between

In react, the way of using css is different from the traditional way
-Introducing external style files
Newstyle/App.css

.box{    margin-left: 50px;    margin-top: 50px;}.box *{    margin:auto 5px;}
Copy after login

Introduce this css file in App.js

import &#39;../style/App.css&#39;
Copy after login

It should be noted here that in react, the class attribute should be written as className, because class is a reserved word of JavaScript

    render(){
        return (            <p className="box">
                <button>+</button>
                <button>-</button>
                <span>当前点击次数</span>
                <span>{this.state.count}</span>
            </p>
        )
    }
Copy after login

How does React work? The whole process of making a react case from scratch

  • Use JavaScript objects to declare styles

    render(){
        const style={
            marginLeft:&#39;50px&#39;,
            marginTop:&#39;50px&#39;
        }
        const item = {
            margin:&#39;auto 5px&#39;
        }
        return (            <p style={style}>
                <button style={item}>+</button>
                <button style={item}>-</button>
                <span style={item}>当前点击次数</span>
                <span style={item}>{this.state.count}</span>
            </p>
        )
    }
Copy after login

The running effect is the same as Figure 1-4

When using the object declaration style, use camelCase, which is camel case

  • Write the style object directly into html

    render(){
        return (            <p style={{marginLeft:&#39;50px&#39;,marginTop:&#39;50px&#39;}}>
                <button style={{margin:&#39;auto 5px&#39;}}>+</button>
                <button style={{margin:&#39;auto 5px&#39;}}>-</button>
                <span style={{margin:&#39;auto 5px&#39;}}>当前点击次数</span>
                <span style={{margin:&#39;auto 5px&#39;}}>{this.state.count}</span>
            </p>
        )
    }
Copy after login

As you can see, the content in the style attribute uses two layers of braces, of which the outer braces are React expression, the inner braces are JavaScript object

The effect of the above three css writing methods It’s the same. In the following examples, in order to make the code simple and intuitive, the method of introducing external css files is adopted

按钮事件

接下来为两个按钮增加点击事件,react中的点击事件为onClick,它与html中的onclick有一些区别,在这里不进行详细描述。我们为加号按钮增加事件处理函数increment,为减号增加事件处理函数decrement。在increment,让state中的count的值加1,在decrement中,让state中count的值减1

注意点:

事件函数绑定this
修改state的方式

import React from &#39;react&#39;;
import &#39;../style/App.css&#39;class App extends React.Component{

    constructor(props){        super(props);        this.state = {            count:0
        }        this.increment = this.increment.bind(this);        this.decrement = this.decrement.bind(this);
    }
   increment(){        this.setState({count:this.state.count+1})
    }
    decrement(){        this.setState({count:this.state.count-1})
    }
    render(){        return (
            

当前点击次数 {this.state.count}

) } } export default App;
Copy after login
  • 修改state中的数据,要调用setState函数来进行设置

  • 定义普通的的函数来处理事件,需要在构造函数中与this进行绑定,否则在函数内部,thisundefined

此时我们在页面点击按钮,就能看到效果了

让绑定this的方式完美一些

在上面的代码中,我们可以看到,事件处理函数要在构造函数中调用bind函数来绑定this,在这里我们只有两个函数,在复杂引用中可能有更多的函数,要是每一个函数都要这么绑定一次,对于有强迫症或者洁癖的开发人员来说是一件非常闹心且痛苦的事情。因此我们要使用更加简洁的方式

请看代码

import React from &#39;react&#39;;
import &#39;../style/App.css&#39;class App extends React.Component{
    constructor(props){        super(props);        this.state = {            count:0
        }
    }
    increment  = () => {        this.setState({count:this.state.count+1})
    }
    decrement = () => {        this.setState({count:this.state.count-1})
    }
    render(){        return (
            

当前点击次数 {this.state.count}

) } } export default App;
Copy after login

点击按钮效果完全一样,整个世界都干净了!

从外部传入数据

在前面我们说到,props是用来从外部传递数据的,那么它是如何传递的呢?

在index.js中我们为App标签添加属性name

ReactDOM.render(<App name="当前点击次数"/>, document.getElementById(&#39;root&#39;));
Copy after login

然后修改App.js中的render函数

    render(){
        return (            <p className="box">
                <button onClick={this.increment}>+</button>
                <button onClick={this.decrement}>-</button>
                <span>{this.props.name}</span>
                <span>{this.state.count}</span>
            </p>
        )
    }
Copy after login

运行效果与之前是一样的!

到这里呢,这个简单而又覆盖到react的大部分内容的范例就说完了!上手试试,其实很简单的!

本篇文章到这就结束了(想看更多就到PHP中文网React使用手册栏目中学习),有问题的可以在下方留言提问。

The above is the detailed content of How does React work? The whole process of making a react case from scratch. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template