初学者的快速入门来学习React.js

什么是React.js? (What is React.js?)

React.js is an open source JavaScript based library for building frontend (user interface) of a web or mobile application.

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

为什么要使用React.js? (Why React.js?)

Every web application core is to have a fast rendering response for better user experience. Because of this ease, users come back often and it leads to higher usage and adaptability.

每个Web应用程序核心都应具有快速的渲染响应,以提供更好的用户体验。 由于这种简便性,用户经常回来,这导致更高的使用率和适应性。

Further, based on how it achieves speed, it is scalable and reusable.

此外,基于它如何达到速度,它是可伸缩可重用的

React.js是如何做到的? (How React.js Does It?)

React.js works at component level. It helps break an app into many small components with their own responsibilities. This makes things simpler and scalable. With this breakdown:

React.js在组件级别工作。 它有助于将一个应用程序分解为许多小组件,各担其责。 这使事情变得更简单和可扩展。 使用此细分:

  • it’s easier to refresh/update a portion of view without reloading an entire page of the app

    刷新/更新视图的一部分而无需重新加载应用程序的整个页面更加容易
  • it leads to build once and reuse across

    它导致一次构建并跨

Another key part of React.js is being declarative. There is an abstraction from details on how to do. This makes it easier to read and understand.

React.js的另一个关键部分是声明性的 。 有关如何做的细节有一个抽象。 这样可以更容易阅读和理解。

A declarative example would be telling my son to make a house craft from paper instead of guiding him with each step of how to get the paper, cut it, paste it to form a house craft. Of course, the assumption here has to be true that my son knows how to make it.

一个说明性的例子是告诉我儿子用纸做家用Craft.io品,而不是指导他如何获取,切割,粘贴以形成家用Craft.io品的每一步。 当然,这里的假设必须是真的,我儿子知道如何做到。

A quick comparison with jQuery here (it’s imperative) – it would need details on how to build the house craft.

jQuery进行快速比较(这势在必行)–它需要有关如何建造房屋的详细信息。

Translating the above in JavaScript language world:

在JavaScript语言世界中翻译以上内容:

  • With React – we define how we want a particular component to be rendered and we never interact with DOM to reference later

    使用React –我们定义了如何渲染特定的组件,并且我们以后从未与DOM交互以进行引用
  • With jQuery – we would tell the browser exactly what needs to be done using DOM elements or events need basis

    使用jQuery –我们会告诉浏览器使用DOM元素或事件需要依据的确切内容

主要特点 (Key Features)

The following features help us achieve the above:

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

For the entire React glossary, please refer to this link.

有关整个React词汇表 ,请参考此链接

  • Components – Simple or State

    组件 –简单或状态

    These are small reusable codes that returns a React element to render. This component can have state related aspect based on need.

    这些是小的可重用代码,它们返回一个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>
       );
      }
    }
    
    	
    Quote:
    引用:

    For above example component, use normal HTML syntax: <ComponentExample />

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

  • Virtual DOM

    虚拟DOM

    DOM (Document Object Model) is a structured representation of the HTML elements present on a web page. Traditionally, one would need to get elements out of DOM to make any change. In context of an area of a webpage, it would need a lot more work to refresh it with updated content when needed.

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

    React helps here with its declarative API. A copy of actual DOM is kept in memory which is much faster to change. Once done, React uses its ReactDOM library to sync the virtual representation of UI in memory to the actual DOM.

    React在这里通过其声明性API来提供帮助。 实际DOM的副本将保留在内存中,这可以更快地进行更改。 完成后,React使用其ReactDOM库将内存中UI的虚拟表示同步到实际DOM。

    ReactDOM library internally keeps two VDOMs – one before update and one after. With them, React knows exactly what all to be updated in actual DOM and does all of it on the fly leading much faster updates compared to traditional DOM updates.

    ReactDOM库在内部保留两个VDOM-一个在更新之前,一个在更新之后。 有了它们,React就能准确地知道实际DOM中需要更新的内容,并且可以实时进行所有操作,从而比传统DOM更新要快得多。

    Quote:
    引用:

    React.js has a library ReactDOM to access and modify the actual DOM.

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

    To render HTML on a webpage, use: ReactDOM.render()

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

  • JSX (JavaScript eXtension)

    JSX (JavaScript eXtension)

    JSX is a syntax extension to JavaScript that follows XML rules. It’s more of a helpful tool than requirement in React as mentioned below in their website:

    JSX是遵循XML规则JavaScript语法扩展。 如下面在他们的网站中提到的,它比React中的要求更有用:

    Quote:
    引用:

    React doesn’t require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code

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

    JSX converts HTML tags into React elements that are placed in DOM without any commands like createElements(), etc.

    JSX将HTML标签转换为放置在DOM中的React元素,而无需使用诸如createElements()等命令。

    // 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'));
    
    	
    Quote:
    引用:

    Normally, we can’t assign an HTML tag to a JavaScript variable but we can with JSX!

    通常,我们不能将HTML标签分配给JavaScript变量,但是我们可以使用JSX!

  • Unidirectional data flow

    单向数据流

    React implements one way reactive data flow. It uses flux as a pattern to keep data unidirectional. Interpret it as you often nest child components within higher order parent components. Snapshot of state is passed across from parent to child components via props (readonly, cannot be updated) and updates from child to parent happen via callbacks bound to some control on child component.  

    React实现了一种React式数据流的方式。 它使用flux作为一种模式来保持数据单向。 解释它,就像您经常将子组件嵌套在高阶父组件中一样。 状态快照通过prop(只读,无法更新)从父组件传递到子组件,而从子组件到父组件的更新是通过绑定到子组件上某些控件的回调发生的。

  • ES6 compatible

    兼容ES6

    React library is ES6 (ECMAScript 2015 or JavaScript 6) enabled and thus makes it easier to write code in React. Among all changes to standardize JavaScript in ES6, Classes introduction is one of them which plays a critical role in React. 

    React库启用了ES6(ECMAScript 2015或JavaScript 6) ,因此可以更轻松地在React中编写代码。 在ES6中标准化JavaScript的所有更改中, Classes引入是其中之一,它在React中起着至关重要的作用。

  • Lifecycle

    生命周期

    Each React component has a lifecycle that helps write a code at a specific time during the flow as per need.  

    每个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>
            );  
        }; 
    }
    	
Quote:
引用:

For the entire React glossary, please refer to this link.

有关整个React词汇表 ,请参考此链接

样例应用程序设置 (Sample Application Setup)

We will explore and understand more from React’s demo app. We will jump start our sample app bootstrapped with Create React App.

我们将通过React的演示应用程序探索和了解更多信息。 我们将快速启动由Create React App引导的示例应用程序

I used yarn create react-app demo-react-app and opened the created directory in IDE that looked like:

我使用yarn create react-app demo-react-app并在IDE中打开创建的目录,如下所示:

default react project structure

With the above, once I ran yarn start in root folder demo-react-app, the app was up and running without any code change. We can see the default app hosted in browser at the following url: http://localhost:3000/.

通过以上操作,一旦我在根文件夹demo-react-app中运行yarn start ,该应用程序便已启动并运行,而无需更改任何代码。 我们可以在以下网址中浏览器中托管默认应用程序: http:// localhost:3000 /

default home page

A quick look at a few key files that connect dots that lead to the above UI view:

快速浏览一些关键点,这些关键点将点连接到上面的UI视图:

  • public/index.html

    public / index.html

    Base file which we browse using URL. We see the HTML defined in it. For now, the element to notice would be a div named root.

    使用URL浏览的基本文件。 我们看到其中定义的HTML 。 现在,要注意的元素将是一个名为rootdiv

  • src/index.js

    src / index.js

    Located at root of app, is like an entry file (like main) for app that has code like below:

    位于应用程序的根目录,就像应用程序的入口文件(如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();
    
    	

    It imported React and related library, CSS file for app, a component named App. After this, it defines a render method which displays whatever is defined in component App as page root element.

    它导入了React和相关库,用于appCSS文件,一个名为App组件 。 此后,它定义了一个render方法,该方法将组件App定义的任何内容显示为页面根元素。

  • src/App.js

    src / App.js

    Defines a function component of React that returns an HTML with React logo and a link to render.

    定义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.org"
              target="_blank"
              rel="noopener noreferrer"
            >
              Learn React
            </a>
          </header>
        </div>
      );
    }
    
    export default App; 
    
    	
    问:index.js如何与index.html建立联系? (Q: How did index.js got connected with index.html?)

    Create React App uses Webpack with html-webpack-plugin underneath. This Webpack uses src/index.js as an entry point. Because of this, index.js comes into picture and all other modules referenced in it. With html-webpack-plugin configuration, it automatically adds the script tag in html page.

    Create React App使用Webpack及其下面的html-webpack-plugin 。 该Webpack使用src / index.js作为入口点 。 因此, index.js成为图片以及其中引用的所有其他模块。 使用html-webpack-plugin配置,它会自动在html页面中添加脚本标签。

现在让我们来看看对应用程序的一些修改! (Let’s see with few modifications to the app now!)

Specifically, I will be changing the flavour of the above three files to play around.

具体来说,我将更改上述三个文件的风格以进行播放。

Few new files reference:

很少有新文件参考:

  1. AppHola.js file for a HelloWorld kind of change – displays my name instead of other texts

    用于HelloWorld更改的AppHola.js文件–显示我的名字而不是其他文本

    • Introduction – simple display of texts

      简介–简单显示文字
    • Clock/counters auto updating

      时钟/计数器自动更新
    • Random color generator that updates background color of defined area

      随机颜色生成器,可更新定义区域的背景色

    AppNavigation.js (has portion of pages updated)

    AppNavigation.js (已更新部分页面)

5273225/demo-app.gif

Given this was for beginners, I have not added too much of complexity to the app. I have tried to keep it as simple possible with some variance of what all can be tried.

考虑到这是针对初学者的,我没有为应用程序增加太多复杂性。 我尝试过尽可能简单地进行尝试,但可以尝试一些变化。

There are plenty of imports that can be used. For example, in our demo app, to have navigation, we have used a navigation router react-router-dom import (run npm i react-router-dom --save inside root folder).

有很多可以使用的进口商品。 例如,在演示应用程序中,要进行导航,我们使用了导航路由器react-router-dom导入(在文件夹中运行npm i react-router-dom --save )。

  • For navigtion menu:

    对于导航菜单:

    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>
        );
      }
    }
    	
  • For Introduction menu item (returned plain simple HTML back with some text):

    对于“简介”菜单项(返回带有一些文本的普通简单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>
        );
      }
    }
    	
  • For Counter menu item (used state component using a peek into ReactJS life cycle - componentDidMountcomponentWillUnmount):

    对于计数器菜单项(使用一个窥视到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>
        );
      }
    }
    	
  • For Colors menu item (wired the HTML input click event to a client script that changes background color at runtime):

    对于“颜色”菜单项(将HTML 输入 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>
            );
        }
    }
    	

Hope this short guide/tutorial gives a broad overview about React.JS and how to start development of the same. Keep learning!

希望这篇简短的指南/教程能够对React.JS及其启动方式进行广泛的概述。 保持学习!

翻译自: https://www.codeproject.com/Articles/5273225/Beginners-Quick-Start-to-Learn-React-js

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值