search
HomeWeb Front-endJS TutorialWhat classes define components in React

What classes define components in React

May 26, 2018 pm 01:58 PM
reactdefinitioncomponents

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>          </p>
<h1 id="hello-this-state-name">hello,{this.state.name}</h1>
<br>          <button onclick="{this.switchName}">{this.state.name==="Tom"? "Jerry":"Tom"}</button><br>        <br>      );<br>   }<br>}   <br>ReactDOM.render(<br>  <greetinginput></greetinginput>,document.getElementById("root")<br>);</span>

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>
          </p><h1 id="hello-this-state-name">hello,{this.state.name}</h1>
          <button>{this.state.name==="Tom"? "Jerry":"Tom"}</button>
              );
   }
}   
ReactDOM.render(  <greetinginput></greetinginput>,document.getElementById("root")
);

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>
          </p><h1 id="hello-this-state-name">hello,{this.state.name}</h1>
          <button> this.switchName(e)}>{this.state.name==="Tom"? "Jerry":"Tom"}</button>
              );
   }
}   
ReactDOM.render(  <greetinginput></greetinginput>,document.getElementById("root")
);

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

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

相信看了本文案例你已经掌握了方法,更多精彩请关注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
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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools