React components have endless magic and great flexibility. We can play with many tricks in the design of components. But it is very important to ensure the Single responsibility principle of the component: it can make our components simpler and more convenient to maintain, and more importantly, it can make the components more reusable. This article mainly shares with you several advanced methods of decomposing React components, hoping to help you.
However, how to decompose a complex and bloated React component may not be a simple matter. This article introduces three methods of decomposing React components from the shallower to the deeper.
Method 1: Cut render() method
This is the easiest method to think of: when a component renders many elements, you need to try to separate the rendering logic of these elements. The fastest way is to split the render() method into multiple sub-render methods.
It will be more intuitive if you look at the following example:
class Panel extends React.Component { renderHeading() { // ... } renderBody() { // ... } render() { return ( <div> {this.renderHeading()} {this.renderBody()} </div> ); } }
Careful readers will quickly discover that this does not actually decompose the component itself. The Panel component still maintains its original state, props, and class methods.
How to really reduce component complexity? We need to create some subcomponents. At this time, it will definitely be a good try to adopt functional components/stateless components supported and recommended by the latest version of React:
const PanelHeader = (props) => ( // ...);const PanelBody = (props) => ( // ...);class Panel extends React.Component { render() { return ( <div> // Nice and explicit about which props are used <panelheader></panelheader> <panelbody></panelbody> </div> ); } }
Compared with the previous method, this subtle improvement is revolutionary.
We created two new unit components: PanelHeader and PanelBody. This brings convenience to testing, and we can directly test different components separately. At the same time, with the help of React's new algorithm engine React Fiber, the rendering efficiency of the two unit components is optimistically expected to be significantly improved.
Method Two: Template Component
Back to the starting point of the problem, why does a component become bloated and complicated? One is that there are many and nested rendering elements, and the other is that there are many changes within the component, or there are multiple configurations.
At this point, we can transform the component into a template: the parent component is similar to a template and only focuses on various configurations.
I still need to give an example to make it clearer.
For example, we have a Comment component, which has multiple behaviors or events.
At the same time, the information displayed by the component changes according to the user's identity:
Whether the user is the author of this comment;
Whether this comment is saved correctly;
Different permissions
-
etc...
will cause different display behaviors of this component.
At this time, instead of confusing all the logic together, maybe a better approach is to use React to transfer the characteristics of React element. We transfer React element between components, so that it is more like a powerful template. :
class CommentTemplate extends React.Component { static propTypes = { // Declare slots as type node metadata: PropTypes.node, actions: PropTypes.node, }; render() { return ( <div> <commentheading> <avatar></avatar> // Slot for metadata <span>{this.props.metadata}</span> </commentheading> <commentbody></commentbody> <commentfooter> <timestamp></timestamp> // Slot for actions <span>{this.props.actions}</span> </commentfooter> </div> ... ) } }
At this point, our real Comment component is organized as:
class Comment extends React.Component { render() { const metadata = this.props.publishTime ? <publishtime></publishtime> : <span>Saving...</span>; const actions = []; if (this.props.isSignedIn) { actions.push(<likeaction></likeaction>); actions.push(<replyaction></replyaction>); } if (this.props.isAuthor) { actions.push(<deleteaction></deleteaction>); } return <commenttemplate></commenttemplate>; } }
metadata and actions are actually the React elements that need to be rendered under specific circumstances.
For example:
If this.props.publishTime exists, metadata is
; The opposite is Saving....
If the user has logged in, it needs to be rendered (that is, the actions value is)
and ; If it is the author himself, the content that needs to be rendered must be added with
.
Method Three: High-Order Components
In actual development, components are often contaminated by other requirements.
Imagine a scenario like this: We want to count the click information of all links on the page. When the link is clicked, a statistics request is sent, and this request needs to contain the id value of the document of this page.
A common approach is to add code logic to the life cycle functions componentDidMount and componentWillUnmount of the Document component:
class Document extends React.Component { componentDidMount() { ReactDOM.findDOMNode(this).addEventListener('click', this.onClick); } componentWillUnmount() { ReactDOM.findDOMNode(this).removeEventListener('click', this.onClick); } onClick = (e) => { // Naive check for <a> elements if (e.target.tagName === 'A') { sendAnalytics('link clicked', { // Specific information to be sent documentId: this.props.documentId }); } }; render() { // ... } }</a>
Several problems with doing this are:
Related component Document In addition to its main logic: displaying the main page, it has other statistical logic;
If there is other logic in the life cycle function of the Document component, then this Components will become more ambiguous and unreasonable;
statistical logic code cannot be reused;
Component reconstruction and maintenance will become more complicated difficulty.
In order to solve this problem, we proposed the concept of higher-order components: higher-order components (HOCs). Without explaining this term obscurely, let’s look directly at how to reconstruct the above code using higher-order components:
function withLinkAnalytics(mapPropsToData, WrappedComponent) { class LinkAnalyticsWrapper extends React.Component { componentDidMount() { ReactDOM.findDOMNode(this).addEventListener('click', this.onClick); } componentWillUnmount() { ReactDOM.findDOMNode(this).removeEventListener('click', this.onClick); } onClick = (e) => { // Naive check for <a> elements if (e.target.tagName === 'A') { const data = mapPropsToData ? mapPropsToData(this.props) : {}; sendAnalytics('link clicked', data); } }; render() { // Simply render the WrappedComponent with all props return <wrappedcomponent></wrappedcomponent>; } } ... }</a>
It should be noted that the withLinkAnalytics function does not change the WrappedComponent component itself, let alone Will change the behavior of the WrappedComponent component. Instead, a new wrapped component is returned. The actual usage is:
class Document extends React.Component { render() { // ... } } export default withLinkAnalytics((props) => ({ documentId: props.documentId }), Document);
In this way, the Document component still only needs to care about the parts it should care about, and withLinkAnalytics gives the ability to reuse statistical logic.
The existence of high-order components perfectly demonstrates React’s innate compositional capabilities. In the React community, react-redux, styled-components, react-intl, etc. have generally adopted this approach. It is worth mentioning that the recompose class library makes use of high-order components and carries them forward to achieve "brain-expanding" things.
The rise of React and its surrounding communities has made functional programming popular and sought after. I think the ideas about decomposing and composing are worth learning. At the same time, a suggestion for development and design is that under normal circumstances, do not hesitate to split your components into smaller and simpler components, because this can lead to robustness and reuse.
Related recommendations:
React component life cycle instance analysis
The most complete method to build React components
Detailed explanation of how store optimizes React components
The above is the detailed content of Several advanced methods for decomposing React components. For more information, please follow other related articles on the PHP Chinese website!

在react中,canvas用于绘制各种图表、动画等;可以利用“react-konva”插件使用canvas,该插件是一个canvas第三方库,用于使用React操作canvas绘制复杂的画布图形,并提供了元素的事件机制和拖放操作的支持。

在react中,antd是基于Ant Design的React UI组件库,主要用于研发企业级中后台产品;dva是一个基于redux和“redux-saga”的数据流方案,内置了“react-router”和fetch,可理解为应用框架。

React不是双向数据流,而是单向数据流。单向数据流是指数据在某个节点被改动后,只会影响一个方向上的其他节点;React中的表现就是数据主要通过props从父节点传递到子节点,若父级的某个props改变了,React会重渲染所有子节点。

因为在react中需要利用到webpack,而webpack依赖nodejs;webpack是一个模块打包机,在执行打包压缩的时候是依赖nodejs的,没有nodejs就不能使用webpack,所以react需要使用nodejs。

在react中,forceupdate()用于强制使组件跳过shouldComponentUpdate(),直接调用render(),可以触发组件的正常生命周期方法,语法为“component.forceUpdate(callback)”。

react是组件化开发;组件化是React的核心思想,可以开发出一个个独立可复用的小组件来构造应用,任何的应用都会被抽象成一颗组件树,组件化开发也就是将一个页面拆分成一个个小的功能模块,每个功能完成自己这部分独立功能。

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。

react和reactdom的区别是:ReactDom只做和浏览器或DOM相关的操作,例如“ReactDOM.findDOMNode()”操作;而react负责除浏览器和DOM以外的相关操作,ReactDom是React的一部分。


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

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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
