React component project (detailed tutorial)
This article shares with you the entire process of writing React component project practices through examples. Friends who are interested in this can refer to it.
When I first started writing React, I saw many ways to write components. There are a hundred ways to write a hundred tutorials. While React itself has matured, there doesn't seem to be a "right" way to use it. So I (the author) summarize here the experience of using React that our team has accumulated over the years. I hope this article is useful to you, whether you are a beginner or a veteran.
Before you start:
We use ES6 and ES7 syntax. If you are not very clear about the difference between display components and container components, it is recommended that you start by reading this article. If you have any suggestions or questions Duqing left a message in the comments about class-based components
Nowadays, React components are generally developed using class-based components. Next we will write our component in the same line:
1 2 3 4 5 |
|
I like css in javascript very much. However, this method of writing styles is still too new. So we introduce css files in each component. Moreover, locally introduced imports and global imports will be separated by a blank line.
Initializing State
1 2 3 4 5 6 7 8 |
|
You can use the old method to initialize state
in constructor
. More related information can be found here. But we choose a clearer approach.
Also, we make sure to add export default
in front of the class. (Translator's note: Although this may not be correct when using redux).
propTypes and defaultProps
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
propTypes
and defaultProps
are static properties. Define it as early as possible in the component class so that other developers can notice it immediately when reading the code. They can serve as documentation.
If you use React 15.3.0 or higher, you need to introduce the prop-types
package instead of using React.PropTypes
. More content moves here.
All your components should have prop types.
Method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
|
In class components, when you pass methods to child components, you need to ensure that they are called using the correct this. This is usually done when passing it to a child component: this.handleSubmit.bind(this)
.
It’s much simpler to use the ES6 arrow method. It automatically maintains the correct context (this
).
Pass a method to setState
In the above example, there is this line:
1 |
|
setState
It is actually asynchronous! In order to improve performance, React will call setState
that is called multiple times together. Therefore, the state may not necessarily change immediately after calling setState
.
So, when calling setState
, you cannot rely on the current state value. Because i doesn't know what value it is.
Solution: Pass a method to setState
, and pass the state value before the call as a parameter to this method. Take a look at the example:
1 |
|
Thanks to Austin Wood for the help.
Disassemble the component
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
|
If there are multiple lines of props
, each prop should occupy a separate line. Just like the above example. The best way to achieve this goal is to use a set of tools: Prettier
.
Decorator
1 2 |
|
If you know some libraries, such as mobx, you can use the above example to decorate class component. A decorator is a method that passes a class component as a parameter.
Decorators can write more flexible and readable components. If you don’t want to use a decorator, you can do this:
1 2 3 4 |
|
Closure
Try to avoid passing closures in child components, such as:
1 2 3 4 5 6 7 |
|
Note: If input
is a React component, this will automatically trigger its redrawing, regardless of whether other props have changed.
Consistency checking is the most resource-consuming part of React. Don't add extra work here. The best way to handle the problem in the above example is to pass in a class method, which will be more readable and easier to debug. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
|
Method component
This type of component has no state, no props, and no methods. They are pure components and contain the least amount of content that causes changes. Use them often.
propTypes
1 2 3 4 5 6 7 8 9 |
|
We define propTypes
before the declaration of the component.
Decompose Props and defaultProps
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
Our component is a method. Its parameters are props
. We can extend this component like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
Now we can also use default parameters to play the role of default props, which has good readability. If expanded
is not defined, then we set it to false
.
However, try to avoid using the following examples:
1 |
|
Looks modern, but the method is unnamed.
如果你的Babel配置正确,未命名的方法并不会是什么大问题。但是,如果Babel有问题的话,那么这个组件里的任何错误都显示为发生在 <>里的,这调试起来就非常麻烦了。
匿名方法也会引起Jest其他的问题。由于会引起各种难以理解的问题,而且也没有什么实际的好处。我们推荐使用function
,少使用const
。
装饰方法组件
由于方法组件没法使用装饰器,只能把它作为参数传入别的方法里。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
只能这样处理:export default observer(ExpandableForm)
。
这就是组件的全部代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
条件判断
某些情况下,你会做很多的条件判断:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
这么多层的条件判断可不是什么好现象。
有第三方库JSX-Control Statements可以解决这个问题。但是与其增加一个依赖,还不如这样来解决:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
使用大括号包起来的IIFE,然后把你的if
表达式都放进去。返回你要返回的组件。
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
vue.js element-ui tree树形控件改iview的方法
The above is the detailed content of React component project (detailed tutorial). 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











After rain in summer, you can often see a beautiful and magical special weather scene - rainbow. This is also a rare scene that can be encountered in photography, and it is very photogenic. There are several conditions for a rainbow to appear: first, there are enough water droplets in the air, and second, the sun shines at a low angle. Therefore, it is easiest to see a rainbow in the afternoon after the rain has cleared up. However, the formation of a rainbow is greatly affected by weather, light and other conditions, so it generally only lasts for a short period of time, and the best viewing and shooting time is even shorter. So when you encounter a rainbow, how can you properly record it and photograph it with quality? 1. Look for rainbows. In addition to the conditions mentioned above, rainbows usually appear in the direction of sunlight, that is, if the sun shines from west to east, rainbows are more likely to appear in the east.

The expansion of the virtual market is inseparable from the circulation of virtual currency, and naturally it is also inseparable from the issue of virtual currency transfers. A common transfer error is the address copy error, and another error is the chain selection error. The transfer of virtual currency to the wrong chain is still a thorny problem, but due to the inexperience of transfer operations, novices often transfer the wrong chain. So how to recover the wrong chain of virtual currency? The wrong link can be retrieved through a third-party platform, but it may not be successful. Next, the editor will tell you in detail to help you better take care of your virtual assets. How to retrieve the wrong chain of virtual currency? The process of retrieving virtual currency transferred to the wrong chain may be complicated and challenging, but by confirming the transfer details, contacting the exchange or wallet provider, importing the private key to a compatible wallet, and using the cross-chain bridge tool

In daily shooting, many people encounter this situation: the photos on the camera seem to be exposed normally, but after exporting the photos, they find that their true form is far from the camera's rendering, and there is obviously an exposure problem. Affected by environmental light, screen brightness and other factors, this situation is relatively normal, but it also brings us a revelation: when looking at photos and analyzing photos, you must learn to read histograms. So, what is a histogram? Simply understood, a histogram is a display form of the brightness distribution of photo pixels: horizontally, the histogram can be roughly divided into three parts, the left side is the shadow area, the middle is the midtone area, and the right side is the highlight area; On the left is the dead black area in the shadows, while on the far right is the spilled area in the highlights. The vertical axis represents the specific distribution of pixels

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.

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.

Having the right documentation and tutorials at your fingertips is crucial to using Java frameworks effectively. Recommended resources include: SpringFramework: Official Documentation and Tutorials SpringBoot: Official Guide Hibernate: Official Documentation, Tutorials and Practical Cases ServletAPI: Official Documentation, Tutorials and Practical Cases JUnit: Official Documentation and Tutorials Mockito: Official Documentation and Tutorials

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

How to master Bootstrap customization and component usage includes: 1. Use CSS variables and Sass preprocessor for style customization; 2. Deeply understand and modify component structure and behavior. Through these methods, a unique user interface can be created to improve the responsiveness and user experience of the website.
