65.9K
CodeProject 正在变化。 阅读更多。
Home

React.js 初学者快速入门

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.79/5 (14投票s)

2020 年 7 月 8 日

CPOL

6分钟阅读

viewsIcon

22220

downloadIcon

179

学习、理解并快速启动 ReactJS

什么是 React.js?

React.js 是一个开源的基于 JavaScript 的库,用于构建 Web 或移动应用程序的前端(用户界面)。

为什么选择 React.js?

每个 Web 应用程序的核心都要求**快速渲染响应**,以提供更好的用户体验。由于这种易用性,用户会经常回来,从而带来更高的使用率和适应性。

此外,根据其实现速度的方式,它是**可伸缩**和**可重用**的。

React.js 是如何做到的?

React.js 在**组件**层面工作。它有助于将应用程序分解成许多拥有各自职责的小组件。这使得事情更简单、更具可伸缩性。通过这种分解,

  • 可以更轻松地刷新/更新视图的一部分,而无需重新加载应用程序的整个页面
  • 实现一次构建,多处重用

React.js 的另一个关键部分是**声明性**。它抽象了“如何做”的细节。这使得它更易于阅读和理解。

一个声明性的例子是告诉我的儿子用纸做一所房子模型,而不是一步一步地指导他如何取纸、剪纸、粘贴成房子模型。当然,这里的前提必须是我的儿子知道如何制作它。

这里与 *jQuery* 进行快速比较(它是命令式的)——它需要关于如何构建房子模型的详细信息。

将上述内容翻译成 JavaScript 语言世界

  • 使用 React – 我们定义我们希望特定组件如何渲染,并且我们从不与 DOM 交互以供将来引用
  • 使用 jQuery – 我们将根据需要使用 DOM 元素或事件来准确告诉浏览器需要做什么

主要特点

以下功能帮助我们实现上述目标

有关完整的 *React 术语表*,请参阅 此链接.

  • 组件 – 简单或有状态

    这些是返回 React 元素进行渲染的小型可重用代码。此组件可以根据需要具有与状态相关的方面。

    // Simple component - a Function Component
    // props - input to React component - data passed from parent caller
    function ComponentExample(props) {
      return <h1>Hola! {props.name}</h1>;
    }
    
    // Simple component - a Class Component
    class ComponentExample extends React.Component {
      render() {
        return <h2>Hola! {this.props.name}</h2>;
      }
    }
    
    // State based component
    // Needed when data associated with component change over time
    // Can be asynchronous and modified via this.setState
    class ComponentExample extends React.Component {
      constructor(props) {
        super(props);
        this.state = {author: "Sandeep Mewara"};
      }
      render() {
        return (
          <div>
            <h2>Hola! {this.props.name}</h2>
            <p>Author: {this.state.author}</p>
          </div>
       );
      }
    }
    引用

    对于上述示例组件,使用正常的 HTML 语法:<ComponentExample />

  • 虚拟DOM

    DOM(文档对象模型)是网页上 HTML 元素的结构化表示。传统上,需要从 DOM 中获取元素才能进行任何更改。在网页的某个区域中,当需要更新内容时,需要做更多的工作来刷新它。

    React 通过其声明式 API 在这里提供了帮助。实际 DOM 的副本保存在内存中,更改起来要快得多。完成后,React 使用其 ReactDOM 库将内存中 UI 的虚拟表示同步到实际 DOM。

    ReactDOM 库内部保留两个 VDOM – 一个更新前,一个更新后。通过它们,React 精确地知道实际 DOM 中所有要更新的内容,并即时完成所有操作,从而比传统的 DOM 更新快得多。

    引用

    React.js 有一个名为 ReactDOM 的库来访问和修改实际 DOM。

    要在网页上渲染 HTML,请使用: ReactDOM.render()

  • JSX (JavaScript eXtension)

    JSX 是 JavaScript 的语法扩展,遵循 XML 规则。它更多的是一个有用的工具,而不是 React 中的要求,如下面他们的网站所述

    引用

    React 不需要使用 JSX,但大多数人发现它在 JavaScript 代码中处理 UI 时作为视觉辅助很有帮助

    JSX 将 HTML 标签转换为 React 元素,这些元素无需任何命令(如 createElements() 等)即可放置在 DOM 中。

    // Example with JSX
    const testHtml = <h2>Hola! Sandeep Mewara</h2>;
    ReactDOM.render(testHtml, document.getElementById('root'));
    
    // Same above example without JSX
    const testHtml = React.createElement('h2', {}, 'Hola! Sandeep Mewara');
    ReactDOM.render(testHtml, document.getElementById('root'));
    引用

    通常,我们不能将 HTML 标签赋值给 JavaScript 变量,但使用 JSX 就可以!

  • 单向数据流

    React 实现单向响应式数据流。它使用 flux 作为 一种模式 来保持数据单向流动。可以理解为,您通常将子组件嵌套在更高阶的父组件中。状态快照通过 props(只读,无法更新)从父组件传递到子组件,而子组件到父组件的更新通过绑定到子组件上某个控件的回调发生。

  • 兼容 ES6

    React 库支持 ES6 (ECMAScript 2015 或 JavaScript 6),因此编写 React 代码变得更容易。在 *ES6* 中标准化 JavaScript 的所有更改中,Classes 的引入是其中之一,它在 React 中扮演着关键角色。

  • 生命周期

    每个 React 组件都有一个生命周期,这有助于根据需要在流的特定时间编写代码。

    // Use class for any local state & lifecycle hooks
    class TestClass extends Component 
    {  
        // first call to component when it is initiated
        constructor(props) 
        {    
            // with it, 'this' would refer to this component
            super(props); 
            // some local state initialized 
            this.state = {currentdate: new Date()};
        };   
        
        // executes before the initial render
        componentWillMount() {    
         
        };  
        
        // executes after the initial render
        componentDidMount() {  
    
        };
    
        // executes when component gets new props
        componentWillReceiveProps() {   
              
        };
    
        // executes before rendering with new props or state
        shouldComponentUpdate() {   
              
        };
        
        // executes before rendering with new props or state
        componentWillUpdate() {   
            
        };
    
        // executes after rendering with new props or state
        componentDidUpdate() {   
              
        };
        
        // executes before component is removed from DOM
        componentWillUnmount() {   
              
        };
    
        // HTML to be displayed by the component rendering 
        render() 
        {    
            return (      
                <h1>Current Date: {this.state.currentdate.toString()}</h1>
            );  
        }; 
    }
    
引用

有关完整的 *React 术语表*,请参阅 此链接

示例应用程序设置

我们将从 React 的演示应用程序中探索和理解更多。我们将使用 Create React App 启动我们的示例应用程序。

我使用了 yarn create react-app demo-react-app 并在 IDE 中打开了创建的目录,它看起来像

default react project structure

完成上述操作后,一旦我在根文件夹 *demo-react-app* 中运行 yarn start,应用程序无需任何代码更改即可启动并运行。我们可以在以下 URL 上的浏览器中看到默认应用程序:https://:3000/

default home page

快速查看几个关键文件,它们连接了导致上述 UI 视图的点

  • public/index.html

    我们使用 URL 浏览的基础文件。我们看到其中定义的 HTML。目前,需要注意的元素是一个名为 rootdiv

  • src/index.js

    位于应用程序根目录,就像应用程序的入口文件(如 main),其中包含如下代码

    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    import App from './App';
    import * as serviceWorker from './serviceWorker';
    
    ReactDOM.render(
      <React.StrictMode>
        <App />
      </React.StrictMode>,
      document.getElementById('root')
    );
    
    // If you want your app to work offline and load faster, you can change
    // unregister() to register() below. Note this comes with some pitfalls.
    // Learn more about service workers: https://bit.ly/CRA-PWA
    serviceWorker.unregister();

    它导入了 React 和相关库、应用程序的 CSS 文件以及一个名为 App组件。在此之后,它定义了一个 render 方法,该方法将组件 App 中定义的所有内容显示为页面根元素。

  • src/App.js

    定义了一个 React 函数组件,它返回一个带有 React 标志和要渲染的链接的 HTML。

    import React from 'react';
    import logo from './logo.svg';
    import './App.css';
    
    function App() {
      return (
        <div className="App">
          <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <p>
              Edit <code>src/App.js</code> and save to reload.
            </p>
            <a
              className="App-link"
              href="https://reactjs.ac.cn"
              target="_blank"
              rel="noopener noreferrer"
            >
              Learn React
            </a>
          </header>
        </div>
      );
    }
    
    export default App; 
    问:index.js 是如何与 index.html 连接起来的?

    Create React App 底层使用了 Webpack 和 html-webpack-plugin。这个 Webpack 使用 *src/index.js* 作为 入口点。因此,*index.js* 及其引用的所有其他模块都会被引入。通过 *html-webpack-plugin* 配置,它会自动在 html 页面中添加 script 标签。

现在让我们对应用程序进行一些修改!

具体来说,我将更改上述三个文件的风格来试验。

几个新文件引用

  1. AppHola.js 文件用于类似 HelloWorld 的更改 – 显示我的名字而不是其他文本
  2. AppNavigation.js(部分页面已更新)
    • 简介 – 简单显示文本
    • 时钟/计数器自动更新
    • 随机颜色生成器,更新定义区域的背景颜色

5273225/demo-app.gif

鉴于这是为初学者准备的,我没有给应用程序增加太多的复杂性。我试图尽可能保持简单,并提供一些可以尝试的不同变体。

有许多可以使用的导入。例如,在我们的演示应用程序中,为了实现导航,我们使用了导航路由器 react-router-dom 导入(在 *root* 文件夹中运行 npm i react-router-dom --save)。

  • 对于导航菜单
    class Navigation extends Component {
      render() {
        return (
            <HashRouter>
            <div>
              <h1>React.js Application</h1>
              <ul className="header">
                <li><NavLink exact to="/">Introduction</NavLink></li>
                <li><NavLink to="/counters">Continous Counter</NavLink></li>
                <li><NavLink to="/colors">Random Color</NavLink></li>
              </ul>
              <div className="content">
                <Route exact path="/" component={Introduction}/>
                <Route path="/counters" component={Counters}/>
                <Route path="/colors" component={Colors}/>
              </div>
            </div>
            </HashRouter>
        );
      }
    }
    
  • 对于简介菜单项(返回了带有文本的纯 HTML)
    class Introduction extends Component {
      render() {
        return (
          <div>
            <h2>Hola!</h2>
            <p>This is a ReactJS based sample application</p>
            <p>built for learning and explaining demo use to beginners.</p>
            <br />
            <line></line>
            <p>------- </p>
            <p>
            <a
              className="App-link"
              href="https://learnbyinsight.com"
              target="_blank"
            >
              Sandeep Mewara
            </a></p>
          </div>
        );
      }
    }
    
  • 对于计数器菜单项(使用了状态组件,窥视了 *ReactJS* 生命周期中的 componentDidMountcomponentWillUnmount
    class Counters extends Component {
      constructor(props) {
        super(props)
    
        this.state = {
            time : Date(Date.now()).toString(),
            delay : 200,
            start : Date(Date.now()).toString(),
            counter: 0
        }
      }
    
      componentDidMount() {
          this.interval = setInterval(() => 
            { 
              this.setState({
                time: Date(Date.now()).toString(),
                counter: this.state.counter+1
              })
            })
      };
    
      componentWillUnmount() {
          clearInterval(this.interval);
      };
    
      render() {
        return (
          <div>
              <h2>Timer!</h2>
              <hr></hr>
              <p>
                  Counter started at: {this.state.start}
              </p>
              <hr></hr>
              <p>
                  Counter: {this.state.counter}
              </p>
              <hr></hr>
              <p>
                  Current Local Time: {this.state.time}
              </p>
              <hr></hr>
          </div>
        );
      }
    }
    
  • 对于颜色菜单项(将 HTML input click 事件连接到客户端脚本,该脚本在运行时更改背景颜色)
    class Colors extends Component {
        constructor(props) {
            super(props)
    
            this.state = {
                randomBackColor : '#070707'
            }
        }
        
        ChangeBackColor = () => {
            var rgbColorCode = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
            this.setState({
                randomBackColor : rgbColorCode
            })
        };
    
        render() {
            return (
                <div>
                    <div style={{ backgroundColor: this.state.randomBackColor, padding:30 }}>
                        <p>This regions background color would change on button click</p>
                        <input type='button' value="Click Me!" onClick={this.ChangeBackColor} />
                    </div>
                    <div className='static'>
                        <p> This region will not be affected with button click</p>
                    </div>
                </div>
            );
        }
    }
    

 

希望这篇简短的指南/教程能让您对 React.JS 及其开发入门有一个大致的了解。持续学习!

历史

  • 2020年7月8日:初始版本
  • 2020年7月11日:更新
© . All rights reserved.