效果演示

image.png

html代码

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <div id="app"></div>
  10. </body>
  11. <script src="./react.js"></script>
  12. <script>
  13. let ele = React.createElement(
  14. 'div',
  15. {
  16. id: 'app',
  17. className: 'box',
  18. style: { color: 'red', fontSize: '23px' },
  19. },
  20. '哈哈哈',
  21. React.createElement('i', null, '呵呵'),
  22. React.createElement(
  23. 'p',
  24. null,
  25. 'hello',
  26. React.createElement('b', null, '666')
  27. )
  28. );
  29. ReactDOM.render(ele, document.getElementById('app'));
  30. </script>
  31. </html>


javascript代码

  1. let ReactModule = (function () {
  2. function Element(type, props, children) {
  3. this.type = type;
  4. this.props = props;
  5. this.children = children
  6. let _this = this;
  7. this.fn = function (str) {
  8. return str.replace(/[A-Z]/g, function (a) {
  9. return '-' + a.toLowerCase()
  10. })
  11. }
  12. this.render = function () {
  13. let ele = document.createElement(_this.type)
  14. _this.props && Object.keys(_this.props).forEach(key => {
  15. switch (key) {
  16. case 'className':
  17. ele.setAttribute('class', _this.props[key])
  18. break;
  19. case 'style':
  20. let str = '';
  21. Object.keys(_this.props[key]).forEach(item => {
  22. str += `${_this.fn(item)}: ${_this.props[key][item]};`
  23. })
  24. console.log(str, 'str++++')
  25. ele.setAttribute('style', str)
  26. break;
  27. case 'htmlFor':
  28. ele.setAttribute('for', _this.props[key])
  29. break;
  30. default:
  31. ele.setAttribute(key, _this.props[key])
  32. break;
  33. }
  34. })
  35. this.children.forEach(item => {
  36. item instanceof Element ?
  37. ele.appendChild(item.render()) :
  38. ele.appendChild(document.createTextNode(item));
  39. })
  40. return ele;
  41. }
  42. }
  43. let React = {
  44. createElement(type, props, ...children) {
  45. return new Element(type, props, children)
  46. }
  47. }
  48. let ReactDOM = {
  49. render: function (ele, container) {
  50. container.appendChild(ele.render())
  51. }
  52. }
  53. return {
  54. init: function () {
  55. window.ReactDOM = ReactDOM
  56. window.React = React;
  57. }
  58. }
  59. })()
  60. ReactModule.init()