preface

Hello everyone, I’m Wangly19, and this time I’m sharing my article from October. Just catch up with the nuggets essay series, I hope you can support me more.

During the two months of learning React, I spent most of my time reading the source code of Vuant-Ui@vue3. I have to say that I got some great help. In fact, most of the ideas were improved or the experience was applied in the project. Most of the time, when writing a component, most of it is split, and very little of it is written directly into a JSX or.vue file. As a result, component writing becomes very artistic.

I also started to reflect on some of my own problems. I did not think too much about component performance and component granularity before, but now I have to think about component solutions from both business and other aspects. QAQ.

In fact, many friends will ask why the React component read the source code of vant, it is not a melon to buy watermelon stall. Here I would like to talk about the reasons. Actually, I still look at the source code of Vant because of vue3. I mainly want to see the differentiation comparison of composition and hook to write components, so as to understand the understanding of business logic in different directions of the two frameworks. As you read through, composition components and stateless components are written very much alike. Let’s cut the chatter and get to the point.

Some shortcomings or mistakes can be pointed out in the comments section.

Considering the Angle

When writing components, there are more or less just a few angles to consider. We are also in the separation, reorganization, splicing and other directions. It is summed up in writing components to consider points can also be summarized as follows:

  • Component classification
  • The degree of coupling
  • Divide the degree
  • reliance

Component classification

Presentation class components

Most of the time, our components fall into one of the following categories. The most commonly used are presentation and interaction components, and most businesses are made up of both. For example, as shown in the figure below, the item option on the front page of JD shopping is a presentation class component. It does not have very complex interaction. The only thing it does is to display data through the value of props, without more and more in-depth logical interaction. So it’s a presentation component.

Interactive component

In for example, the choice of JD shopping goods specifications of the interface is a typical interactive components, when you click on the specifications of the label at the same time, your price and the selected data will change, and the status of the goods but also in real time, when the goods out of stock, the confirm button will prohibit the user for further operation and so on different status. This is an interactive component.

Data component

For non-perceptive data class components, they are generally provided by frameworks or libraries. For example, the React-Router and React-Redux are both data class components, which prepare the required data at the beginning of the Web application for subsequent use. It is therefore a component that belongs to an aggregation channel.

HOC high-level components

From higher-order functions to higher-order components, most of the time, in order to be able to reuse some logic, often use the HOC, with business expanding, the component that forgiveness also will need to support, if some logical component is used repeatedly, so this time, you need according to the view of the differences between considering high-order component of a split, Whether vue2 mixins or Custom hooks, most of them provide simple logic reuse for developers.

The degree of coupling

Through the above several ways of components for a component has a preliminary understanding, then the component coupling the, ideally in Java, as we all know, there are many ways in which a class we hope that by method to describe the behavior patterns and characteristics of this class, so most of the time, a method is usually do one thing, They don’t intervene too much. Similarly, in the component, the render function is very messy, without a little annotation may form a reading dead zone, other people if there is no documentation, very difficult to understand the meaning of the code, so there are many previous trees, descendants are really cool situation, a good component library most of its code is decoupled, We can perform some component decoupling depending on the role of different component types.

The instance

In the Vant UI, I find their component splitting very clear now. Just recently the Taro framework ran into component library issues and used a Popup component as an example. As can be seen from the code, Popup is divided into two parts, one is content and the other is overflow mask. We declare it through different render methods, and finally organize it in return. Each render method only does a logic processing or the introduction of other associated logic, without interfering with each other. In this way, when others read components, they can start from the feature block, quickly clarify the logic, and carry out Bug fixes or features.

import React from 'react'
import { View } from '@tarojs/components'

import VtIcon from '@/components/vt-icon'
import VtOverflow from '@/components/vt-overflow'
import { CSSTransition } from 'react-transition-group'

import classNames from 'classnames'
import PropTypes from 'prop-types'
import '@/styles/vt-popup.scss'

function VtPopUp (props) {
  const {
    customStyle,
    className,
    overlayClass,
    overlayStyle,
    children,
    overlay,
    show,
    zIndex,
    position,
    round,
    transition,
  } = props

  /** * overflow click event */
  const handelOverFlowClick = () = > { 
    console.log('click overflow')}/** * Mask layer */
  const renderOverlay = () = > {
    if (overlay) {
      return (
        <VtOverflow 
          show={ show } 
          customStyle={ overlayStyle }
          className={ classNames(['vt-overflow-hidden',
            overlayClass,])}onClick={ handelOverFlowClick} / >)}}/ * * *TODO:Close the icon */
  const renderCloseIcon = () = >{}/** * Popup component */
  const renderPopup = () = > {
    return (
      show ? <View
        v-show={props.show}
        style={{
          zIndex.. customStyle
        }}
        className={classNames([`vt-popup`,
            `vt-popup--The ${position} `,round && `vt-popup--round`,
            className,])} >
        {children}
        {/* {renderCloseIcon()} */}
      </View> : null)}const renderTransition = () = > {
    const name = position === 'center' ? 
      'vt-fade' : 
      `vt-popup-slide-${position}`;

    return (
      <CSSTransition
        in={true}
        timeout={1000}
        unmountOnExit
        classNames={ transition || name }
        appear={true}// turn on the style shown for the first time
      >   
        {renderPopup()}
      </CSSTransition>)}return (
    <>
      { renderOverlay() }
      { renderTransition() }
    </>
  )
}

VtPopUp.propTypes = {
  className: PropTypes.string,
  customStyle: PropTypes.object,
  children: PropTypes.element,
  show: PropTypes.bool, / / show the popup
  zIndex: PropTypes.oneOfType([ / / zIndex hierarchy
    PropTypes.string,
    PropTypes.number,
  ]),
  duration: PropTypes.oneOfType([ // Animation length
    PropTypes.string,
    PropTypes.number,
  ]),
  overlayClass: PropTypes.string, // Mask style
  overlayStyle: PropTypes.object, // Mask style
  overlay: PropTypes.bool, // Whether to display masks
  lockScroll: PropTypes.bool, 
  lazyRender: PropTypes.bool, / / lazy loading
  closeOnClickOverlay: PropTypes.bool // Whether to close after clicking the mask layer

}

VtPopUp.defaultProps = {
  show: false.overlay: true.zIndex: 2.position: 'center'.lockScroll: true.lazyRender: true.closeOnClickOverlay: true,}export default VtPopUp

Copy the code

reliance

Having said component coupling, let’s talk about component partitioning. We all know that components can be used as global components and layout components. Each component has its own variable domain. The child component has the state of the child component, and the parent component has the state of the parent component. Most of the data passed by props comes from the props of the parent component,

Therefore, it is necessary to consider how dependent the state is when the parent component state is updated. Compared with the dirty data, the heavily dependent component often changes greatly due to the fluttering of the butterfly’s wings.

Therefore, in the write component, we appropriately carry out the calculation of the property wrap, to prevent changes due to other reasons. Update components that only need to be updated. Therefore, if your component dependency calculations are heavy and performance costly, use the Memo package as usual.

const realInfo = useMemo(() = > {
// Component content, only
}, [props.payid, props.openid])
Copy the code

To sum up:

  • Avoid componentspropsTransition requantization,propsThe more (not the more data, but the more dependencies) the more frequently components occurrender.
  • Components with high performance costs can be used appropriatelyMemo HookMemorized data
  • Try to maintain most of the state internally rather than pass it all down
  • Manage component states. Do not abuse unknown states.

conclusion

React is full of understandable concepts that you may not be able to use. However, most students who are limited by business have not considered the separation of components and the flow of data. It is common to see a JSX file that is 1000 ~ 1500 lines in size. At this point, it is very bloated, developers know? I know, but limited by business, I have no time to deal with too many component schemes. When I stack them up slowly, the code becomes very bad. When I come back a month later, I need to clear up some ideas before I know the meaning of the code. React did the same thing, Vue did the same thing, but in the end there were a lot of people claiming React was better than Vue. But that in itself is a difficult question to answer, as different developers use the same tool differently and create different values.

The shovel is used by some people to dig, and by the same people to cook. React is the spade. It’s just a tool. It doesn’t have any restrictions on its use.

If you find it helpful, you can give it a thumbs up. I really want a gift package. This article will be published in October. If anything is wrong, please feel free to communicate in the comments section and learn together.

QAQ.