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!

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 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.

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'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.

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 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 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 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.


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

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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.

Zend Studio 13.0.1
Powerful PHP integrated development environment

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