Why does the front end use the idea of componentization? It is analyzed by an example

Keywords: Javascript

In normal projects, why do we use the idea of component to write code?

In fact, the reason is very simple!!! When we write the code, we find that the code will appear in other places, and we want to reuse it, or our colleagues are interested in using it. At this time, we need to reuse the code through componentization, otherwise the workload is really ..

The following is an example:


This is a good function. If you write it to me, it's easy

HTML

 <body>
    <div class='wrapper'>
      <button class='like-btn'>
        <span class='like-text'>Give the thumbs-up</span>
        <span>(Pretend to have a little icon of a hand)</span>
      </button>
    </div>
  </body>

JavaScript

  const button = document.querySelector('.like-btn')
  const buttonText = button.querySelector('.like-text')
  let isLiked = false
  button.addEventListener('click', () => {
    isLiked = !isLiked
    if (isLiked) {
      buttonText.innerHTML = 'cancel'
    } else {
      buttonText.innerHTML = 'Give the thumbs-up'
    }
  }, false)

When the code is finished, your colleague comes over and says that he likes your button very much. He also wants to use the like function you wrote. At this point, the problem will come, and you will find that this implementation method is fatal: your colleagues should copy the whole button and the structure inside, and the whole JavaScript code. Such an implementation has no reusability.

Simple componentization

Here's a function that turns a string into a DOM

// ::String => ::Document
const createDOMFromString = (domString) => {
  const div = document.createElement('div')
  div.innerHTML = domString
  return div
}

After processing by component

 class LikeButton {
    constructor () {
      this.state = { isLiked: false }
    }

    changeLikeText () {
      const likeText = this.el.querySelector('.like-text')
      this.state.isLiked = !this.state.isLiked
      likeText.innerHTML = this.state.isLiked ? 'cancel' : 'Give the thumbs-up'
    }

    render () {
      this.el = createDOMFromString(`
        <button class='like-button'>
          <span class='like-text'>Give the thumbs-up</span>
          <span>(Pretend to have a little icon of a hand)</span>
        </button>
      `)
      this.el.addEventListener('click', this.changeLikeText.bind(this), false)
      return this.el
    }
  }

Use components elsewhere

Now the reusability of this component is very good. Your colleagues just need to instantiate it and insert it into the DOM.

  const wrapper = document.querySelector('.wrapper')

  const likeButton1 = new LikeButton()
  wrapper.appendChild(likeButton1.render())

  const likeButton2 = new LikeButton()
  wrapper.appendChild(likeButton2.render())

Posted by Submerged on Sat, 04 Apr 2020 09:29:00 -0700