1 . 声明式和命令式 (Declarative vs Imperative)
声明式和命令式是两种编程范式。react是声明式的,jquery那样直接操作dom是命令式
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.
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.
声明式就像你告诉你朋友画一幅画,你不用去管他怎么画的细节
命令式就像按照你的命令,你朋友一步步把画画出来
换言之
- 命令式编程:命令“机器”如何去做事情(how),这样不管你想要的是什么(what),它都会按照你的命令实现。
- 声明式编程:告诉“机器”你想要的是什么(what),让机器想出如何去做(how)。
2 . 来点代码
点击一个按钮,改变颜色
命令式:
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 (); }}
注意到什么不一样了么?
react没有去修改dom,只是声明了页面应该是什么样子(根据不同的state).
放到整个应用层面也是一样的道理,我们更加需要关心的是整个应用和页面的框架结构。
参考链接: