Skip to content

03.React是什么

React的官方文档上有一句非常醒目的话:

React is a JavaScript library for building user interfaces.

但是这个描述非常抽象,我们先来了解React的具体价值再回过头来理解这句话。

React有什么价值

我们有个需求,通过下面两种方式来实现,观察两者的区别,就能体现出React的价值::

  1. 用原始的JavaScript代码来实现
  2. 用React来实现

案例需求

在页面上显示一个按钮,按钮显示的文字内容为:Hello, Count: 0,每点击一次该按钮,Count后的数字加1。

案例实现-原始版

html
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <div id="root">
            <div id="content" onclick="changeText()">Click Me, Count: 0</div>
        </div>
    </body>
    <style>
        #content{
            font-size:22px;
            border: 1px solid gray;
            cursor: pointer;
            padding: 6px 10px;
            display: inline-block;
            border-radius: 10px;
        }
    </style>
    <script lang="javascript">
        let count = 0
        function changeText(){
            count ++
            document.getElementById('content').innerText = "Click Me, Count: " + count
        }
    </script>
</html>

案例实现-React版

html
<html>
  <head>
    <title>Test</title>
    <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
    <!-- Don't use this in production: -->
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  </head>
  <style>
    #content{
        font-size:22px;
        border: 1px solid gray;
        cursor: pointer;
        padding: 6px 10px;
        display: inline-block;
        border-radius: 10px;
    }
  </style>
  <body>
    <div id="root"></div>
    <script type="text/babel">
      function MyFunctionComponent() {
        let [count, setCount] = React.useState(0)
        return <div id="content" onClick={()=>setCount(++count)}>Click Me, Count: {count}</div>
      }

      const container = document.getElementById('root');
      const root = ReactDOM.createRoot(container);
      root.render(<MyFunctionComponent />);

    </script>
    <!--
      Note: this page is a great way to try React but it's not suitable for production.
      It slowly compiles JSX with Babel in the browser and uses a large development build of React.
    -->
  </body>
</html>

注意,案例的React版本的实现仅仅是为了验证原理,其中的代码只适用于学习用,不适用于生产环境,本教程的所有示例同理。如果不了解React版本的代码为什么这么实现,暂时不用关心实现细节,后续内容会涉及到对相关语法详细而深入的讲解。

根据上面案例的原始版本实现和React版实现,即使不知道React的语法,不去深究React版本实现的细节,我们也能从宏观上进行比较二者的一些不同:

  1. 案例的React版本实现中引入了三个外部链接
  2. 相较于原始版本,React版本的代码实现只关注了变量count值的变化,并没有手动去操作DOM

根据上面观察到的两点差异,我们可以得出这样一个结论:React本质上就是一个根据数据变化来操作DOM的工具库。这个结论与本小节开始提到的React定义是相吻合的。我们在导学课中提到过,React的核心工作是数据驱动视图,所谓数据驱动视图,就是指根据数据的变化改变视图。

官方资料

2013年6月5日,Pete Hunt发表了一篇名为Why did we build React?的博客,阐述了React诞生的原因以及React的一些关键特征,有下面几点值得我们关注:

  1. React isn’t an MVC framework.
  2. React doesn’t use templates.
  3. Reactive updates are dead simple.
  4. HTML is just the beginning.

基于 VitePress 构建