<script src="https://cdn.bootcss.com/react/16.7.0-alpha.2/umd/react.development.js"></script> <script src="https://cdn.bootcss.com/react-dom/16.7.0-alpha.2/umd/react-dom.production.min.js"></script> <script> let number = 0 ;
let span = React.createElement('span',{className:'red'},number); ReactDOM.render(span,document.querySelector('#root'))
let add = document.querySelector('#add');
add.addEventListener('click',function(){ number += 1;
let span = React.createElement('span',{className:'red'},number); ReactDOM.render(span,document.querySelector('#root')) }) </script> </body> </html>
<script src="https://cdn.bootcss.com/react/16.7.0-alpha.2/umd/react.development.js"></script> <script src="https://cdn.bootcss.com/react-dom/16.7.0-alpha.2/umd/react-dom.production.min.js"></script> <script> let number = 0 ;
render()
let add = document.querySelector('#add');
add.addEventListener('click',function(){ number += 1; render() })
function render(){ let span = React.createElement('span',{className:'red'},number); ReactDOM.render(span,document.querySelector('#root')) } </script> </body> </html>
<script src="https://cdn.bootcss.com/react/16.7.0-alpha.2/umd/react.development.js"></script> <script src="https://cdn.bootcss.com/react-dom/16.7.0-alpha.2/umd/react-dom.production.min.js"></script> <script> let number = 0 ; let onClickButton = ()=>{ number += 1; render(); } let onClickButton2 = ()=>{ number -= 1; render(); } render()
function render(){ let span = React.createElement('span',{className:'red'},number); let button = React.createElement('button',{onClick:onClickButton},'+'); let button2 = React.createElement('button',{onClick:onClickButton2},'-'); let div = React.createElement('div',{className:'container'},span,button,button2); ReactDOM.render(div,document.querySelector('#root')) } </script> </body> </html>
千万不要以为 render的时候是重新造了一个 dom
react没那么傻
它是局部刷新, 不会整个更新
点击add后 虚拟的 1 会和 页面里0 比较后发现只变了 中间部分的文案 其他没变
JSX的发明
第一次优化
1 2 3 4 5 6 7 8 9 10 11 12
function render(){ let h = React.createElement; let span = h('span',{className:'red'},number); let button = h('button',{onClick:onClickButton},'+'); let button2 = h('button',{onClick:onClickButton2},'-'); let div = h('div',{className:'container'}, span, button, button2 ); ReactDOM.render(div,document.querySelector('#root')) }
第二次优化,移除临时变量,直接用函数嵌套
1 2 3 4 5 6 7 8 9
function render(){ let h = React.createElement; let div = h('div',{className:'container'}, h('span',{className:'red'},number), h('button',{onClick:onClickButton},'+'), h('button',{onClick:onClickButton2},'-') ); ReactDOM.render(div,document.querySelector('#root')) }