聲明式和命令式

  1 . 聲明和命令式 (Declarative vs Imperativereact

  聲明和命令式是兩種編程範式。react是聲明式的,jquery那樣直接操做dom是命令式jquery

Alright here’s a metaphor.編程

Declarative Programming is like asking your friend to draw a landscape. You don’t care how they draw it, that’s up to them.app

Imperative Programming is like your friend listening to Bob Ross tell them how to paint a landscape. While good ole Bob Ross isn’t exactly commanding, he is giving them step by step directions to get the desired result.框架

      聲明式就像你告訴你朋友畫一幅畫,你不用去管他怎麼畫的細節dom

  命令式就像按照你的命令,你朋友一步步把畫畫出來this

     換言之spa

  • 命令式編程:命令「機器」如何去作事情(how),這樣無論你想要的是什麼(what),它都會按照你的命令實現。
  • 聲明式編程:告訴「機器」你想要的是什麼(what),讓機器想出如何去作(how)。

 2 . 來點代碼3d

     點擊一個按鈕,改變顏色code

  命令式:

const container = document.getElementById(‘container’);
const btn = document.createElement(‘button’);
btn.className = ‘btn red’;
btn.onclick = function(event) {
 if (this.classList.contains(‘red’)) {
   this.classList.remove(‘red’);
   this.classList.add(‘blue’);
 } else {
   this.classList.remove(‘blue’);
   this.classList.add(‘red’);
 }
};
container.appendChild(btn);

   聲明式(react):

class Button extends React.Component{
  this.state = { color: 'red' }
  handleChange = () => {
    const color = this.state.color === 'red' ? 'blue' : 'red';
    this.setState({ color });
  }
  render() {
    return (<div>
      <button 
         className=`btn ${this.state.color}`
         onClick={this.handleChange}>
      </button>
    </div>);
  }
}

 

   注意到什麼不同了麼?

   react沒有去修改dom,只是聲明瞭頁面應該是什麼樣子(根據不一樣的state).

   放到整個應用層面也是同樣的道理,咱們更加須要關心的是整個應用和頁面的框架結構。

 

 

  參考連接:https://codeburst.io/declarative-vs-imperative-programming-a8a7c93d9ad2

相關文章
相關標籤/搜索