Table of Contents
Class components: " > Class components:
Question 1: Should the constructor be defined in the class component? )? " >Question 1: Should the constructor be defined in the class component? )?
Question 3: Should the binding event be performed in the constructor()? " > Question 3: Should the binding event be performed in the constructor()?
Home Web Front-end JS Tutorial What classes define components in React

What classes define components in React

May 26, 2018 pm 01:58 PM
react definition components

This time I will show you what class definition components are in React, and what are the precautions for using class definition components in React. The following is a practical case, let's take a look.

Not long after I started learning React, I saw examples of using components of class in the teacher’s tutorial, but there were some conflicts with the information, which raised some questions:

  • Do we need to define the constructor function constructor() in the class component?

  • #Should props parameters be passed in to super()?

  • #Should the binding event be performed in the constructor()?

Find information, summarized as follows:

Class components:

Define components canUse functionsDefinition components and class definition components ()

Let’s briefly talk about the difference between function definition components and class definition components:

  • State cannot be used in function components, nor can the lifecycle methods of components be used;

  • Function components are all display components, accepting props and rendering DOM;

  • #There is no this in the function component, but it still needs to be bound in the class component Trivial things like this, such as: use this.props to replace props in the render() method;

  • You can use local state state and Lifecycle methods.

Class definition component instance:

<span style="color: #000000">class GreetingInput extends React.Component{<br>//构造函数<br>    constructor(props){<br>        super(props);//将props传入到<a href="http://www.php.cn/code/12195.html" target="_blank">构造方法</a>中<br>        this.state={name:"Tom"};//初始化state的值<br>        this.switchName=this.switchName.bind(this);<br>    }<br>//自定义的switchName方法,用作事件处理<br>    switchName(){<br>       if(this.state.name==="Tom"){<br>          this.setState({name:"Jerry"});//修改state的值<br>        }else{<br>          this.setState({name:"Tom"});<br>        }<br>   } <br>//render方法  渲染在UI上的内容<br>   render(){<br>      return(<br>        <p><br>          <h1>hello,{this.state.name}</h1><br>          <button onClick={this.switchName}>{this.state.name==="Tom"? "Jerry":"Tom"}</button><br>        </p><br>      );<br>   }<br>}   <br>ReactDOM.render(<br>  <GreetingInput/>,document.getElementById("root")<br>);</span>
Copy after login

Question 1: Should the constructor be defined in the class component? )?

The concept of class is new in ES6. A class must have a constructor method. If there is no explicit definition in the class, an empty constructor method will be added by default;

Generally, state and binding events need to be initialized in the constructor. Therefore, when state or binding events need to be initialized, the constructor method needs to be explicitly defined and state is initialized in the constructor method. And binding events

Question 2: Do I need to pass in props parameters in super()?

First of all, if the constructor method is explicitly declared, super must be called, that is, only when there is a constructor method, super must be called

I encountered some examples where there is no parameter props passed in super(). How to use super() and super(props)?

React will automatically set props anywhere in the component except the constructor method. Therefore, when using props in the non-constructor method of the component, you do not need to pass it in. , used directly,

But When you want to use props in the constructor, you must pass the props into super, so that Props are accessed in the constructor, otherwise they don’t need to be passed in.

Question 3: Should the binding event be performed in the constructor()?

As mentioned earlier, events generally need to be bound in the constructor, but bind needs to be used. If you do not want to call bind, you can also use the following method:

1. Using the arrow function initialization method, the above example becomes:

class GreetingInput extends React.Component{//构造函数方法    
constructor(props){
        super(props);        
        this.state={name:"Tom"};
        
    }//自定义的switchName方法,用作事件处理   下边用的是属性初始化语法
    switchName=()=>{       
    if(this.state.name==="Tom"){          
    this.setState({name:"Jerry"});
        }else{          
        this.setState({name:"Tom"});
        }
   } 
//render方法  渲染在UI上的内容   
render(){      
return(        
<p>
          <h1>hello,{this.state.name}</h1>
          <button onClick={this.switchName}>{this.state.name==="Tom"? "Jerry":"Tom"}</button>
        </p>      );
   }
}   
ReactDOM.render(  <GreetingInput/>,document.getElementById("root")
);
Copy after login

The this pointer in the function points to the function itself. Therefore, in the constructor of the class, you need Bind the event function to an instance of this class

但箭头函数里的this指针,指向其拥有者,也就是class ,因此一个简易的方式是,在类中尽可能使用箭头函数定义函数

2、在回调函数中使用箭头函数

class GreetingInput extends React.Component{//构造函数方法    
constructor(props){
        super(props);        
        this.state={name:"Tom"};
        
    }//自定义的switchName方法,用作事件处理    
    switchName(){       
    if(this.state.name==="Tom"){          
    this.setState({name:"Jerry"});
        }else{          
        this.setState({name:"Tom"});
        }
   } 
//render方法  渲染在UI上的内容   使用下边这个语法  有个问题就是每次switchName 渲染的时候都会创建一个不同的回调函数   
render(){      
return(        
<p>
          <h1>hello,{this.state.name}</h1>
          <button onClick={(e) => this.switchName(e)}>{this.state.name==="Tom"? "Jerry":"Tom"}</button>
        </p>      );
   }
}   
ReactDOM.render(  <GreetingInput/>,document.getElementById("root")
);
Copy after login

注意:当回调函数作为一个属性值传入低阶组件,上述这种方法可能会进行额外的重新渲染。

我们通常建议在构造函数中绑定或使用属性初始化器语法来避免这类性能问题。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

正则表达式怎么在字符串中提取数字

Vue.js的表单输入绑定
Reactive Form的自定义验证器

The above is the detailed content of What classes define components in React. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to install the Windows 10 old version component DirectPlay How to install the Windows 10 old version component DirectPlay Dec 28, 2023 pm 03:43 PM

Many users always encounter some problems when playing some games on win10, such as screen freezes and blurred screens. At this time, we can solve the problem by turning on the directplay function, and the operation method of the function is also Very simple. How to install directplay, the old component of win10 1. Enter "Control Panel" in the search box and open it 2. Select large icons as the viewing method 3. Find "Programs and Features" 4. Click on the left to enable or turn off win functions 5. Select the old version here Just check the box

The definition and function of MySQL composite primary key The definition and function of MySQL composite primary key Mar 15, 2024 pm 05:18 PM

The composite primary key in MySQL refers to the primary key composed of multiple fields in the table, which is used to uniquely identify each record. Unlike a single primary key, a composite primary key is formed by combining the values ​​of multiple fields. When creating a table, you can define a composite primary key by specifying multiple fields as primary keys. In order to demonstrate the definition and function of composite primary keys, we first create a table named users, which contains three fields: id, username and email, where id is an auto-incrementing primary key and user

What is Discuz? Definition and function introduction of Discuz What is Discuz? Definition and function introduction of Discuz Mar 03, 2024 am 10:33 AM

"Exploring Discuz: Definition, Functions and Code Examples" With the rapid development of the Internet, community forums have become an important platform for people to obtain information and exchange opinions. Among the many community forum systems, Discuz, as a well-known open source forum software in China, is favored by the majority of website developers and administrators. So, what is Discuz? What functions does it have, and how can it help our website? This article will introduce Discuz in detail and attach specific code examples to help readers learn more about it.

PHP, Vue and React: How to choose the most suitable front-end framework? PHP, Vue and React: How to choose the most suitable front-end framework? Mar 15, 2024 pm 05:48 PM

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

How to open the settings of the old version of win10 components How to open the settings of the old version of win10 components Dec 22, 2023 am 08:45 AM

Win10 old version components need to be turned on by users themselves in the settings, because many components are usually closed by default. First we need to enter the settings. The operation is very simple. Just follow the steps below. Where are the win10 old version components? Open 1. Click Start, then click "Win System" 2. Click to enter the Control Panel 3. Then click the program below 4. Click "Enable or turn off Win functions" 5. Here you can choose what you want to open

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

Introduction to PHP interfaces and how to define them Introduction to PHP interfaces and how to define them Mar 23, 2024 am 09:00 AM

Introduction to PHP interface and how it is defined. PHP is an open source scripting language widely used in Web development. It is flexible, simple, and powerful. In PHP, an interface is a tool that defines common methods between multiple classes, achieving polymorphism and making code more flexible and reusable. This article will introduce the concept of PHP interfaces and how to define them, and provide specific code examples to demonstrate their usage. 1. PHP interface concept Interface plays an important role in object-oriented programming, defining the class application

See all articles