React简单解释如何封装组件的demo

前端之家收集整理的这篇文章主要介绍了React简单解释如何封装组件的demo前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. <!DOCTYPE html>
  2. <html>
  3.  
  4. <head>
  5. <Meta charset="utf-8">
  6. <title>Reactjs in 40 </title>
  7. <style media="screen">
  8. .like-btn { font-size: 50px; }
  9. </style>
  10. </head>
  11.  
  12. <body>
  13. <div class='wrapper'></div>
  14. </body>
  15.  
  16. <script type="text/javascript">
  17. /* Component */
  18. class Component {
  19. constructor (props = {}) {
  20. this.props = props
  21. }
  22. setState (state) {
  23. const oldEl = this.el
  24. this.state = state
  25. this.el = this.renderDOM()
  26. if (this.onStateChange) this.onStateChange(oldEl,this.el)
  27. }
  28. renderDOM () {
  29. this.el = createDOMFromString(this.render())
  30. if (this.onClick) {
  31. this.el.addEventListener('click',this.onClick.bind(this),false)
  32. }
  33. return this.el
  34. }
  35. }
  36. const createDOMFromString = (domString) => {
  37. const div = document.createElement('div')
  38. div.innerHTML = domString
  39. return div
  40. }
  41. const mount = (component,wrapper) => {
  42. wrapper.appendChild(component.renderDOM())
  43. component.onStateChange = (oldEl,newEl) => {
  44. wrapper.insertBefore(newEl,oldEl)
  45. wrapper.removeChild(oldEl)
  46. }
  47. }
  48. /* ========================================= */
  49. class LikeButton extends Component {
  50. constructor (props) {
  51. super(props)
  52. this.state = { isLiked: false }
  53. }
  54. onClick () {
  55. this.setState({
  56. isLiked: !this.state.isLiked
  57. })
  58. }
  59. render () {
  60. return `
  61. <button class='like-btn' style="background-color: ${this.props.bgColor}">
  62. <span class='like-text'>
  63. ${this.state.isLiked ? '取消' : '点赞'}
  64. </span>
  65. <span>��</span>
  66. </button>
  67. `
  68. }
  69. }
  70. class RedBlueButton extends Component {
  71. constructor (props) {
  72. super(props)
  73. this.state = {
  74. color: 'red'
  75. }
  76. }
  77. onClick () {
  78. this.setState({
  79. color: 'blue'
  80. })
  81. }
  82. render () {
  83. return `
  84. <div style='color: ${this.state.color};'>${this.state.color}</div>
  85. `
  86. }
  87. }
  88. const wrapper = document.querySelector('.wrapper')
  89. mount(new LikeButton({ bgColor: 'red' }),wrapper)
  90. mount(new LikeButton(),wrapper)
  91. mount(new RedBlueButton(),wrapper)
  92. </script>
  93. </html>

文章链接http://huziketang.com/books/react/lesson2

猜你在找的React相关文章