通过原生JS实现按钮+1/-1

http://js.jirengu.com/qapeb/1/edit?html,js,output
image.png

React实现

思路:只向页面传内容,不从页面获取内容
http://js.jirengu.com/zohububida/1/edit?html,css,js,output
image.png

React要导入React和React-DOM两个库

优化

  1. let h = React.createElement
  2. let number = 0
  3. let onClickButton = () => {
  4. number += 1
  5. render()
  6. }
  7. let onClickButton2 = () => {
  8. number -= 1
  9. render()
  10. }
  11. render()
  12. function render() {
  13. ReactDOM.render(
  14. h('div', {className: 'parent'},
  15. h('span', {className: 'red'}, number),
  16. h('button', {onClick: onClickButton}, '+1'),
  17. h('button', {onClick: onClickButton2}, '-1')),
  18. document.querySelector('#root'))
  19. }

http://js.jirengu.com/tusal/1/edit?html,css,js,output

使用JSX

  1. let number = 0
  2. let onClickButton = () => {
  3. number += 1
  4. render()
  5. }
  6. let onClickButton2 = () => {
  7. number -= 1
  8. render()
  9. }
  10. render()
  11. function render() {
  12. ReactDOM.render(
  13. // React.createElement('div', ...)
  14. <div className='parent'>
  15. <span className='red'>{number}</span>
  16. <button onClick={onClickButton}>+1</button>
  17. <button onClick={onClickButton2}>-1</button>
  18. </div>,
  19. document.querySelector('#root'))
  20. }

http://js.jirengu.com/tusal/2/edit?html,css,js,output
JSX是JS的拓展,用写html的方式写JS
变量要写在{}里
虚拟节点是用对象表示的节点