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 id="fullName">{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>
);
}
}There are two ways of writing, this within the function Pointing is different.
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
}Case 2: When both are executed directly in render.
// 写法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>
);
}Case 3: Give this.fn2.bind(this), bind this action context. // 写法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>
);
} Note, do not confuse it with the method abbreviation of the object in ES6. The following is the method abbreviation of the object Object: Ruan Yifeng ES6: http://es6.ruanyifeng. com/#docs/object

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 , 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>
);
}As shown above, the array inside the tag can be rendered correctly, then there is the following writing method:
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!
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding 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 UseApr 16, 2025 am 12:12 AMPython 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 ResourcesApr 15, 2025 am 12:16 AMPython 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.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


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

Atom editor mac version download
The most popular open source editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

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







