VSCode 插件推荐

image.png
image.png
image.png
image.png
image.png

Hello React

原生JS实现

原生JS是命令式编程

  1. <body>
  2. <h1 class="msg"></h1>
  3. <button class="btn">切换</button>
  4. <script>
  5. const msg = document.querySelector('.msg')
  6. msg.innerHTML = 'hello world'
  7. const btn = document.querySelector('.btn')
  8. btn.addEventListener('click', () => {
  9. msg.innerHTML = 'hello react'
  10. })
  11. </script>
  12. </body>

React实现

react是声明式编程

  1. 必须引入3个依赖(官方文档
    • react: 包含react必须的核心代码
    • react-dom: 用于在不同平台渲染
    • babel: 将 JSX 转译为 react.createElement
  2. script标签必须加 type=”text/babel” 才能使用 JSX 语法
  3. reactDOM.render(参数1:要渲染的内容,参数2:要挂载到的对象)

    1. <body>
    2. <div id="app"></div>
    3. <!-- 必须引入3个依赖 -->
    4. <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
    5. <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
    6. <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    7. <!-- 必须加 type="text/babel" -->
    8. <script type="text/babel">
    9. let message = 'hello world'
    10. const changeMsg = () => {
    11. message = 'hello react'
    12. render() // 需要手动重新渲染
    13. }
    14. const render = () => {
    15. ReactDOM.render(
    16. <div>
    17. <h1>{message}</h1>
    18. <button className="btn" onClick={changeMsg}>切换</button>
    19. </div>,
    20. document.getElementById('app'))
    21. }
    22. render()
    23. </script>
    24. </body>

    React组件化

    点击事件默认调用是 fn.apply(undefined), 所以必须bind(this)

    1. <body>
    2. <div id="app"></div>
    3. <!-- 必须引入3个依赖 -->
    4. <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
    5. <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
    6. <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    7. <!-- 必须加 type="text/babel" -->
    8. <script type="text/babel">
    9. class App extends React.Component {
    10. constructor(){
    11. super()
    12. this.state = {
    13. message: 'hello world'
    14. }
    15. }
    16. changeMsg(){
    17. this.setState({
    18. message: 'hello react'
    19. })
    20. }
    21. render(){
    22. return (
    23. <div>
    24. <h1>{this.state.message}</h1>
    25. <button onClick={this.changeMsg.bind(this)}>切换</button>
    26. </div>
    27. )
    28. }
    29. }
    30. ReactDOM.render(<App />, document.querySelector('#app'))
    31. </script>
    32. </body>