Translation: Liu Xiaoxi
Original link:https://dmitripavlutin.com/7- …
The length of the original textVeryLong, but the content is too attractive to me, still can’t help but to translate it. This article is very helpful for writing reusable and maintainable React components. But because of the length is too long, I divided the article, this article focuses onCombination and reuse. Due to limited level, some translations in this article may not be accurate enough. If you have better ideas, please point them out in the comment area.
More articles to stamp:https://github.com/YvetteLau/ …
I am a dividing line.
Combination
A combined component is made up of smaller specific components.
Composition is a way to create larger components by joining components together. Combination is the core of React.
Fortunately, the combination is easy to understand. Join a group of small fragments to create a bigger one.
Let’s look at a common front-end application combination mode. Application by the head of theheader
At the bottomfooter
On the leftsidebar
, and the effective content of the central joint:
<div id="root"></div>
function Application({ children }) {
return (
<div className="application box">
<Label>Application</Label>
{children}
</div>
);
}
function Header() {
return (
<div className="header box">
<Label>Header</Label>
</div>
)
}
function Footer() {
return (
<div className="header box">
<Label>Footer</Label>
</div>
)
}
function Sidebar({ children }) {
return (
<div className="sidebar box">
<Label>Sidebar</Label>
{children}
</div>
);
}
function Content({ children }) {
return (
<div className="content box">
<Label>Content</Label>
{children}
</div>
)
}
function Menu() {
return (
<div className="menu box">
<Label>Menu</Label>
<div className="description">
<div className="text shorter" />
<div className="text" />
<div className="text shorter" />
<div className="text shorter" />
</div>
</div>
);
}
function Article() {
return (
<div className="article box">
<Label>Article</Label>
<div className="description">
<div className="text shorter" /> <div className="text longer" />
<div className="text shorter" /> <div className="text" />
<div className="text shorter" /> <div className="text" />
<div className="text" /> <div className="text shorter" />
<div className="text shorter" /> <div className="text" />
<div className="text" /> <div className="text shorter" />
<div className="text shorter" /> <div className="text longer" />
<div className="text shorter" /> <div className="longer" />
<div className="text shorter" /> <div className="text" />
<div className="text" /> <div className="text shorter" />
<div className="text shorter" /> <div className="text" />
</div>
</div>
);
}
function Label({ children }) {
return <div className="label"><{children}></div>
}
const app = (
<Application>
<Header />
<Sidebar>
<Menu />
</Sidebar>
<Content>
<Article />
</Content>
<Footer />
</Application>
);
ReactDOM.render(app, document.getElementById('root'));
The application demonstrates how the combination builds the application. This organization organizes the code in such a way that it is expressive and easy to understand.
The combination of React components is natural. This library uses a declarative paradigm, which does not inhibit the expressiveness of combinatorics.
<Application>
By<Header>
、<Sidebar>
<Content>
And<Footer>
Composition.<Sidebar>
There is a<Menu>
Components,<Content>
There is a<Article>
Components.
What is the relationship between combination and single responsibility and encapsulation? Let’s look at it together:
Principle of single responsibilityDescribes how to split requirements into components,EncapsulationDescribes how to organize these components and how to bond the whole system together.
Benefits of Combination
Single responsibility
An important aspect of composition is the ability to compose complex components from specific small components. This divide-and-rule approach helps the combined complex components to conform to SRP principles.
Looking back at previous code snippets,<Application>
Responsible for renderingheader
、footer
、sidebar
And a main body region.
It is meaningful to divide this responsibility into four sub-responsibilities. Each sub-responsibility is implemented by special components, namely<header>
、<sidebar>
、<content>
And<footer>
. These components are then bonded to<Application>
.
Now let’s look at the benefits of combination: through sub-components to achieve a single responsibility, so that<Application>
Components also conform to the principle of single responsibility.
Reusable
Combinations have reusable points. Common logic can be reused by using combined components.
For example, components<Composed1>
And<Composed2>
There are some common codes:
const instance1 = (
<Composed1>
/* Specific to Composed1 code... */
/* Common code... */
</Composed1>
);
const instance2 = (
<Composed2>
/* Common code... */
/* Specific to Composed2 code... */
</Composed2>
);
Code duplication is a bad practice (e.g. changeComposed1
You also need to change the code ofComposed2
How do you make components reuse common code?
First, encapsulate the common code into a new component, such as<Common>
, and then
First, encapsulate the common code in the new component. Secondly,<Composed1>
And<Composed2>
You should use a combination to include<Common>
Component to avoid code duplication, as follows:
const instance1 = (
<Composed1>
<Piece1 />
<Common />
</Composed1>
);
const instance2 = (
<Composed2>
<Common />
<Piece2 />
</Composed2>
);
Reusable components are consistent with not repeating themselves (Don't repeat yourself
) principle. This method can save your energy and time, and is beneficial to code maintenance at a later stage.
Flexible
Inreact
In, a combined component is passed to a subcomponentprops
To control its subcomponents. This brings the benefits of flexibility.
For example, there is a component that needs to display information according to the user’s device. The combination can flexibly meet this requirement:
function ByDevice({ children: { mobile, other } }) {
return Utils.isMobile() ? mobile : other;
}
<ByDevice>{{
mobile: <div>Mobile detected!</div>,
other: <div>Not a mobile device</div>
}}</ByDevice>
<ByDevice>
Combined components, for mobile devices, display:Mobile detected!
; For non-mobile devices, displayNot a mobile device"
.
Efficient
The hierarchical structure of user interfaces that can be combined, therefore, the combination of components is an effective way to build user interfaces.
Note:DRY
In principle, there is no problem in theory, but in practical application, we should avoid dogma. It can only play a guiding role, there is no quantitative standard, otherwise in theory every line of code in a program can only appear once, this is very absurd, other principles are the same, also play a guiding role.
multiplexing
Reusable components, written once and used many times.
Imagine if software development always repeats the wheel. Then when you write code, you cannot use any existing libraries or tools. Even in the same application, you cannot use code that has already been written. In this environment, is it possible to write an application within a reasonable time? No way.
At this time, we should realize the importance of reuse and use existing libraries or codes instead of building wheels repeatedly.
Reuse in Application
According to “don’t repeat yourself” (DRY
) principle, every piece of knowledge must have a single, clear and authoritative expression in the system. This principle suggests avoiding repetition.
Code duplication adds complexity and maintenance, but does not add significant value. Logical updates force you to modify all duplicate code in your application.
Repetition can be solved by reusable components. Write once and use many times.
However, reuse is not cost-free. Only one component is reusable when it meets the principle of single responsibility and has a reasonable package.
Compliance with the principle of single responsibility is essential:
Reusing a component actually means reusing its responsibilities
Components with only one responsibility are the easiest to reuse.
However, when a component has multiple responsibilities incorrectly, its reuse will add a lot of overhead. You only want to reuse one responsibility, but you will also get unnecessary responsibilities. For example, you just want a banana, but when you get a banana, you have to accept all the jungles.
Components that are reasonably packaged. It hides the internal implementation and has definiteprops
So that the component can be used in various occasions requiring reuse.
Reuse third-party library
One working day, you just received the task of adding new features to the application. Wait a few minutes before lifting your sleeve and tapping the code.
The work you want to do has been solved with great probability. Due toReact
It is wise to search for existing solutions first for the very popular and excellent open source community.
examinebrillout/awesome-react-components
Which has a reusable list of components.
Excellent third-party libraries have a structural impact and will promote best practices. In my experience, the most influential one isreact-router
Andredux
.
react-router
Declarative routing is used to build a single page application. Use<Route>
willURL
Associated with components. When a user accesses a matchingURL
The route renders the corresponding component.
redux
Andreact-redux
One-way and predictable application state management is introduced. Asynchronous and impure code (e.g.HTTP
Requests) are extracted from components to conform to the principle of single responsibility and create pure or almost-pure components.
Here is a checklist to determine whether the third-party library is worth using:
- Document: Check whether the library is meaningful
README.md
Files and Detailed Documents - Tested: A prominent feature of trusted libraries is high test coverage
- Maintenance: Look at how often library authors create new features, modify bugs, and perform routine maintenance.
Finally, I would like to thank all my friends who are willing to spend precious time reading this article. If this article gives you some help or inspiration, please don’t be stingy with your praise and Star. Your affirmation is my greatest motivation to move forward.https://github.com/YvetteLau/ …
I recommend paying attention to my public number.