There are three ways to declare react components: 1. Use functional methods to define stateless components; 2. Use the "React.createClass()" method to define components; 3. Use "React.Component()" Methods define components in ES6 style.
The operating environment of this tutorial: Windows7 system, react17.0.1 version, Dell G3 computer.
The way react declares (creates) components:
After the launch of React, there have been three methods of defining react components for different reasons. Methods, different approaches lead to the same goal;
Three specific ways:
Functional definition of stateless components
React.createClass( ) Define components
React.Component() Define components
Although there are three ways to define react components, then these three ways to define components What's the difference? In other words, why do corresponding definitions appear? Let’s briefly introduce it below.
Stateless functional components
The creation of stateless functional components has appeared since React version 0.14. It is used to create pure display components, which are only responsible for display based on the incoming props and do not involve state operations. Specific stateless functional components, the official pointed out:
In most React codes, most components are written as stateless components, which can be built into other components through simple combination; this A design pattern is advocated in which multiple simple applications are combined into one large application.
The stateless functional component is formally represented as a component class with only one render method. It is created in the form of a function or ES6 arrow function, and the component is stateless. The specific creation form is as follows:
function HelloComponent(props, /* context */) { return <div>Hello {props.name}</div> } ReactDOM.render(<HelloComponent name="Sebastian" />, mountNode)
The creation form of stateless components makes the code more readable, and reduces a lot of redundant code, simplifying it to only one render method, which greatly enhances the ability to write a In addition to the convenience of components, stateless components have the following significant features:
The creation form of stateless components makes the code more readable and reduces a lot of redundant code. Simplified to only one render method, which greatly enhances the convenience of writing a component. In addition, stateless components have the following notable features:
-
The component will not be instantiated ization, the overall rendering performance is improved
Because the component is simplified into a function of the render method. Since it is a stateless component, the stateless component will not be instantiated in the process of component instantiation. There is no instance. There is no need to allocate excess memory during the optimization process, thereby improving performance to a certain extent.
-
Components cannot access this object
Stateless components have no instantiation process, so they cannot access objects in component this, such as: this.ref, this.state None can access it. If you want to access, you cannot use this form to create components
-
Components cannot access life cycle methods
Because stateless components do not require component life cycle management and status Management, so the underlying implementation of this form of component will not implement the component's life cycle method. Therefore, stateless components cannot participate in the various life cycle management of components.
Stateless components can only access input props. The same props will get the same rendering results without side effects
Stateless Components are encouraged to be written as simply as possible in large projects to split the originally huge components. In the future, React will also perform a series of optimizations for stateless components, such as meaningless checks and memory allocation, so whenever possible, Use stateless components whenever possible.
React.createClass
React.createClass is the first recommended way to create components in react. This is a React component implemented in ES5's native JavaScript. Its form As follows:
var InputControlES5 = React.createClass({ propTypes: {//定义传入props中的属性各种类型 initialValue: React.PropTypes.string }, defaultProps: { //组件默认的props对象 initialValue: '' }, // 设置 initial state getInitialState: function() {//组件相关的状态对象 return { text: this.props.initialValue || 'placeholder' }; }, handleChange: function(event) { this.setState({ //this represents react component instance text: event.target.value }); }, render: function() { return ( <div> Type something: <input onChange={this.handleChange} value={this.state.text} /> </div> ); } }); InputControlES6.propTypes = { initialValue: React.PropTypes.string }; InputControlES6.defaultProps = { initialValue: '' };
Compared with stateless components, React.createClass and React.Component to be described later create stateful components. These components are to be instantiated and can access the life of the component. cycle method. However, with the development of React, problems with the React.createClass form itself have been exposed:
React.createClass will self-bind function methods (unlike React.Component which only binds the things you need to care about) function) results in unnecessary performance overhead and increases the likelihood of code becoming obsolete.
The mixins of React.createClass are not natural and intuitive enough; the React.Component form is very suitable for higher-order components (Higher Order Components--HOC), which displays the mixins in a more intuitive form More powerful functions, and HOC is pure JavaScript, no need to worry about them being abandoned. For HOC, please refer to "Stateless Components and Higher-Order Components".
React.Component
React.Component是以ES6的形式来创建react的组件的,是React目前极为推荐的创建有状态组件的方式,最终会取代React.createClass形式;相对于 React.createClass可以更好实现代码复用。将上面React.createClass的形式改为React.Component形式如下:
class InputControlES6 extends React.Component { constructor(props) { super(props); // 设置 initial state this.state = { text: props.initialValue || 'placeholder' }; // ES6 类中函数必须手动绑定 this.handleChange = this.handleChange.bind(this); } handleChange(event) { this.setState({ text: event.target.value }); } render() { return ( <div> Type something: <input onChange={this.handleChange} value={this.state.text} /> </div> ); } } InputControlES6.propTypes = { initialValue: React.PropTypes.string }; InputControlES6.defaultProps = { initialValue: '' };
推荐学习:《react视频教程》
The above is the detailed content of There are several ways to declare react components. For more information, please follow other related articles on the PHP Chinese website!

React’s popularity includes its performance optimization, component reuse and a rich ecosystem. 1. Performance optimization achieves efficient updates through virtual DOM and diffing mechanisms. 2. Component Reuse Reduces duplicate code by reusable components. 3. Rich ecosystem and one-way data flow enhance the development experience.

React is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.

React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.