Some details of react that you may not have noticed! (Summarize)
Have you noticed these details in react? The following article summarizes some details of react that you may not have noticed. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
[Related tutorial recommendations: React video tutorial]
Some detailed knowledge points in react:
1. The use of get in components (as a getter for classes)
ES6 knowledge: class classes also have their own The getter and setter are written as follows:
Class Component { constructor() { super() this.name = '' } // name的getter get name() { ... } // name的setter set name(value) { ... } }
The use of get in the react component is as follows:
/* * renderFullName的getter * 可以直接在render中使用this.renderFullName */ get renderFullName () { return `${this.props.firstName} ${this.props.lastName}`; } render() { return ( <div>{this.renderFullName}</div> ) }
So what is the use of getter in the react component? ?
constructor (props) { super() this.state = {}; } render () { // 常规写法,在render中直接计算 var fullName = `${this.props.firstName} ${this.props.lastName}`; return ( <div> <h2>{fullName}</h2> </div> ); }
// 较为优雅的写法:,减少render函数的臃肿 renderFullName () { return `${this.props.firstName} ${this.props.lastName}`; } render () { var fullName = this.renderFullName() <div>{ fullName }</div> }
// 推荐的做法:通过getter而不是函数形式,减少变量 get renderFullName () { return `${this.props.firstName} ${this.props.lastName}`; } render () { <div>{ this.renderFullName }</div> }
If you know Vue, then you know the computed: {} computed property, which also uses getter at the bottom, but the getter of the object is not the getter of the class
// 计算属性,计算renderFullName computed: { renderFullName: () => { return `${this.firstName} ${this.lastName}`; } }
One advantage of Vue's computed is:
Computed properties are compared with function execution: there will be caching, reducing calculations ---> Computed properties will only be re-evaluated when its related dependencies change. .
This means that as long as firstName and lastName have not changed, multiple accesses to the renderFullName calculated property will immediately return the previous calculation results without having to execute the function again.
So does react’s getter also have the advantage of caching? ? ? The answer is: No, the getter in react does not do caching optimization!
2. Component attr and event execution sequence:
A. Parent-child components: In the form of props, the parent passes it to the child
B. The same component: the back covers the front.
Relying on the above rules, in order to make attr have the highest weight, it should be placed in the lowest component, and the position should be as far back as possible.
<-- 父组件Parent | 调用子组件并传递onChange属性 --> <div> <Child onChange={this.handleParentChange} /> </div> <-- 子组件Child | 接收父组件onChange, 自己也有onChange属性 --> <input {...this.props} onChange={this.handleChildChange} />
At this time, the onChange executed by the Child component only executes the handleChildChange event, and the handleParentChange event will not be executed.
- 1. What if you only need to execute handleParentChange manage? ? In input {...this.props} and onChange={this.handleChildChange } Change position.
- #2. What if both events need to be executed? ? In the child component HandlechildChange this.props.handleParentchange
export default Class Child extends Component {
constructor (props) {
super()
this.state = {};
}
// 写法1,这是ES6的类的方法写法
fn1() {
console.log(this)
// 输出 undefined
}
// 写法2,这是react的方法写法
fn2 = () => {
console.log(this)
// 输出:Child {props: {…}, context: {…}, refs: {…}, …}
}
render () {
return (
<div>
<button onClick={this.fn1}>fn1方法执行</button >
<button onClick={this.fn2}>fn2方法执行</button >
</div>
);
}
}
Case 1: When this is not used inside the function, the two are equal.
// 写法1,这是ES6的类的方法写法 fn1() { return 1 + 1 } // 写法2,这是react的方法写法 fn2 = () => { return 1 + 1 }
// 写法1,这是ES6的类的方法写法 fn1() { console.log(this) // Child {props: {…}, context: {…}, refs: {…}, …} } // 写法2,这是react的方法写法 fn2 = () => { console.log(this) // 输出:Child {props: {…}, context: {…}, refs: {…}, …} } render () { return ( <div> <button onClick={() => { this.fn1(); }}>fn1方法执行</button > <button onClick={() => { this.fn2(); }}>fn2方法执行</button > </div> ); }
// 写法1,这是ES6的类的方法写法 fn1() { console.log(this) // Child {props: {…}, context: {…}, refs: {…}, …} } // 写法2,这是react的方法写法 fn2 = () => { console.log(this) // 输出:Child {props: {…}, context: {…}, refs: {…}, …} } render () { return ( <div> <button onClick={this.fn1}>fn1方法执行</button > <button onClick={this.fn2.bind(this)}>fn2方法执行</button > </div> ); }
Reference: https: //doc.react-china.org/docs/lists-and-keys.html
The normal way to write jsx is to write syntax similar to HTML in render, with nested tags< input />
, with js, use { curly brackets }. But I don’t know if you have noticed that Arrays can be nested inside tags and render normally. function NumberList(props) {
const numbers = [1,2,3,4,5];
// listItems是数组numbers通过map返回的,本质也是个数组。
const listItems = numbers.map((number) =>
<li>{number}</li>
);
return (
<ul>
// 可以替换成 [ <li>1</li>, <li>2</li>, .....]
{listItems}
</ul>
);
}
renderItem(name) { const A = <li key={'a'}>A</li>, B = <li key={'b'}>B</li>, C = <li key={'c'}>C</li>, D = <li key={'d'}>D</li>; let operationList; switch (name) { case 1: operationList = [A , B, C] break; case 2: operationList = [B, C, D] break; case 0: operationList = [A] break; } return operationList; } render() { // this.renderItem() 执行结果是数组 return ( <ul>{ this.renderItem() }</ul> ) }
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of Some details of react that you may not have noticed! (Summarize). For more information, please follow other related articles on the PHP Chinese website!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

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.

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.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

JavaScript and WebSocket: Building an efficient real-time search engine Introduction: With the development of the Internet, users have higher and higher requirements for real-time search engines. When searching with traditional search engines, users need to click the search button to get results. This method cannot meet users' needs for real-time search results. Therefore, using JavaScript and WebSocket technology to implement real-time search engines has become a hot topic. This article will introduce in detail the use of JavaScript
