Home > Article > Web Front-end > Several advanced methods for decomposing React components
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.
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 title={this.props.title}/> <PanelBody content={this.props.content}/> </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.
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 user={...}/> // Slot for metadata <span>{this.props.metadata}</span> </CommentHeading> <CommentBody/> <CommentFooter> <Timestamp time={...}/> // 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 time={this.props.publishTime} /> : <span>Saving...</span>; const actions = []; if (this.props.isSignedIn) { actions.push(<LikeAction />); actions.push(<ReplyAction />); } if (this.props.isAuthor) { actions.push(<DeleteAction />); } return <CommentTemplate metadata={metadata} actions={actions} />; } }
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)
If it is the author himself, the content that needs to be rendered must be added with
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() { // ... } }
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 {...this.props} />; } } ... }
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!