react学习预备知识

If you want to learn the basics of React in the time it takes you to drink a cup of coffee, this post is for you.

如果您想在喝杯咖啡的时间里学习React的基础知识,那么这篇文章适合您。

This article aims to provide a beginner-friendly introduction to React, what it is, and why we need it. It assumes you have some understanding of basic JavaScript.

本文旨在提供对React的初学者友好介绍,它的含义以及我们为什么需要它。 假定您对基本JavaScript有所了解。

We will discuss some of its basic concepts and go over what you can build with React.

我们将讨论它的一些基本概念,并介绍您可以使用React构建的内容。

We will also discuss some code, but the overall goal is to gain an intuitive understanding of what React is all about so that you get comfortable with the basics.

我们还将讨论一些代码,但是总体目标是获得对React的全部内容的直观了解,以便您熟悉基础知识。

什么是React? (What is React?)

Developed by Facebook in 2011, React has quickly become one of the most widely used JavaScript libraries. According to HackerRank, 30% of employers look for developers who know React but only about half of the applicants actually have the required knowledge.

由Facebook在2011年开发,React已Swift成为使用最广泛JavaScript库之一。 根据HackerRank的说法 ,有30%的雇主在寻找了解React的开发人员,但实际上只有大约一半的申请人具备所需的知识。

Clearly, React is in high demand in the job market.

显然,React在就业市场上有很高的需求。

So what exactly is React?

那么,React到底是什么?

React is an efficient and flexible JavaScript library for building user interfaces (and React itself is written using JavaScript). It breaks down complex UIs into small, isolated code called “components”. By using these components, React only concerns itself with what you see on the front page of a website.

React是用于构建用户界面的高效且灵活JavaScript库(React本身是使用JavaScript编写的)。 它将复杂的UI分解为称为“组件”的小型隔离代码。 通过使用这些组件,React只关心您在网站首页上看到的内容。

Components are independent and reusable. They can either be JavaScript functions or classes. Either way, they both return a piece of code that represents part of a web page.

组件是独立且可重用的。 它们可以是JavaScript函数或类。 无论哪种方式,它们都返回代表网页一部分的一段代码。

Here’s an example of a function component that renders a <h2> element onto the page:

这是一个将<h2>元素呈现到页面上的功能组件的示例:

function Name() {return <h2>Hi, my name is Joe!</h2>;
}

And here is a class component doing the same rendering:

这是一个执行相同渲染的类组件:

class Person extends React.Component {render() {return <h2>Hi again from Joe!</h2>;}
}

Using a class component takes slightly more effort in that you have to extend React.Component (part of the React library) while a function component is mostly plain JavaScript. However, class components provide certain critical functionalities that function components lack (see Functional vs Class-Components in React).

使用类组件需要花费更多的精力,因为您必须扩展React.Component(React库的一部分),而功能组件主要是纯JavaScript。 但是,类组件提供了某些功能组件所缺少的关键功能(请参见React中的Functional vs Class-Components )。

You may have noticed that there is a strange mixture of HTML and JavaScript inside each component. React actually uses a language called JSX that allows HTML to be mixed with JavaScript.

您可能已经注意到,每个组件中都有HTML和JavaScript的奇怪混合。 React实际上使用一种称为JSX的语言,该语言允许HTML与JavaScript混合。

Not only can you use JSX to return pre-defined HTML elements, you can also create your own. For example, instead of rendering <h2> elements directly in the class component, you can render the functional component which returns the same thing:

您不仅可以使用JSX返回预定义HTML元素,还可以创建自己的元素。 例如,您可以呈现返回相同内容的功能组件,而不是直接在类组件中呈现<h2>元素:

class Person extends React.Component {render() {return <Name />;}
}

Note the self-closing ‘/>’ of the component.

注意组件的自动闭合“ />”。

The power of React starts to become more evident as you can imagine rendering many simple components to form a more complex one.

当您可以想象渲染许多简单的组件以形成更复杂的组件时,React的力量开始变得越来越明显。

To build a page, we can call these components in a certain order, use the results they return, and display them to the user.

要构建页面,我们可以按一定顺序调用这些组件,使用它们返回的结果,并将其显示给用户。

为什么选择React而不是Vanilla JavaScript? (Why Choose React Over Vanilla JavaScript?)

Being able to break down complex UIs through the use of components gives React an edge over vanilla JavaScript (plain JS without any external libraries or frameworks). But what else can React do that places it in such high demand among employers?

能够通过使用组件来分解复杂的UI,使React在原始JavaScript(没有任何外部库或框架的纯JS)方面具有优势。 但是React还能做什么呢,使它在雇主中如此高的需求呢?

Let’s take a look at the differences between how React and vanilla JS handle things.

让我们看一下React和Vanilla JS处理事物之间的区别。

In the previous section, we discussed how React uses components to render UIs. We did not delve into what was happening on the HTML side of things. It may be surprising to learn that the HTML code that pairs with React is really simple:

在上一节中,我们讨论了React如何使用组件来呈现UI。 我们没有深入研究HTML方面的情况。 得知与React配对HTML代码真的很简单可能令人惊讶:

<div id="root"></div>

It is usually just a <div> element with an id that serves as a container for a React app. When React renders its components, it will look for this id to render to. The page is empty before this rendering.

通常它只是一个<div>元素,其ID用作React应用程序的容器。 当React渲染其组件时,它将寻找要渲染到的ID。 呈现之前该页面为空。

Vanilla JS, on the other hand, defines the initial UI right in the HTML.

另一方面,Vanilla JS在HTML中定义了初始UI。

In addition, vanilla JS takes care of functionality while HTML takes care of displaying content (markup).

另外,香草JS负责功能,而HTML负责显示内容(标记)。

In the earlier days of the web, the separation of functionality and markup sounded logical as apps were simpler. However, as complexity grew so did the headaches of maintaining large pieces of JS code.

在网络的早期,功能和标记的分离听起来合乎逻辑,因为应用程序更简单。 但是,随着复杂性的增加,维护大型JS代码的麻烦也增加了。

JS code that updates a piece of HTML can be spread across several files, and developers may have a hard time keeping track of where the code came from. They have to keep things straight in their heads of all the interactions between the code that resides in different files.

更新一段HTML的JS代码可以分布在多个文件中,开发人员可能很难跟踪代码的来源。 他们必须使驻留在不同文件中的代码之间的所有交互始终保持头脑清醒。

React sorts the code into components, where each component maintains all the code needed to both display and update the UI.

React将代码分类为组件,其中每个组件都维护显示和更新UI所需的所有代码。

Updating the UI requires updating the DOM, or document object model (see DOM Manipulation Using JavaScript). This is where React truly shines.

更新UI需要更新DOM或文档对象模型(请参阅使用JavaScript进行DOM操作 )。 这是React真正的亮点。

If you want to access the DOM in vanilla JS, you have to first find it before it can be used. React stores the data in regular JS variables and maintains its own virtual DOM.

如果要在Vanilla JS中访问DOM,则必须先找到它,然后才能使用它。 React将数据存储在常规JS变量中,并维护其自己的虚拟 DOM。

If you want to then update the DOM in vanilla JS, you have to locate the appropriate node and then manually append or remove elements. React automatically updates the UI based on the application state, which we will discuss in more detail in the next section.

如果要在原始JS中更新DOM,则必须找到适当的节点,然后手动添加或删除元素。 React根据应用程序状态自动更新UI,我们将在下一节中对其进行详细讨论。

So the primary reason why we may want to use React over vanilla JS can be summarized in one word: simplicity.

因此,我们可能想在React JS上使用React的主要原因可以概括为一个词:简单性。

With vanilla JS, it’s easy to get lost in a maze of DOM searches and updates. React forces you to break down your app into components which produces more maintainable code.

使用香草JS,很容易迷失在DOM搜索和更新的迷宫中。 React迫使您将您的应用程序分解为可产生更多可维护代码的组件。

Thus, for complex apps you will definitely want to learn React.

因此,对于复杂的应用程序,您肯定会想学习React。

基本的React概念 (Basic React Concepts)

We have already discussed how React uses components to break down complex UIs and JSX to render those components.

我们已经讨论过React如何使用组件分解复杂的UI和JSX来呈现那些组件。

In this section we will talk about some more fundamental concepts of React.

在本节中,我们将讨论React的一些更基本的概念。

州 (State)

As mentioned previously, React updates the UI based on the application state. This state is actually stored as a property of a React class component:

如前所述,React根据应用程序状态更新UI。 此状态实际上存储为React类组件的属性:

class Counter extends React.Component {state = {value: 0};
}

Suppose we have a counter and 2 buttons that either increment or decrement. The value of the counter is rendered onto the page through JSX.

假设我们有一个计数器和2个可以递增或递减的按钮。 计数器的值通过JSX呈现到页面上。

The display counter value is based on the state and we change the state by clicking one of the buttons. Vanilla JS treats a button click as an event and so does React. When such an event occurs, we will call functions that either increment or decrement the counter based on the button clicked. These functions have the code that changes the component state.

显示计数器值基于状态,我们通过单击按钮之一来更改状态。 Vanilla JS将按钮单击视为事件,React也是如此。 当发生此类事件时,我们将调用根据单击的按钮递增或递减计数器的函数。 这些函数具有更改组件状态的代码。

Here’s an example of such a counter:

这是此类计数器的示例:

class Counter extends React.Component {state = {value: 0};
handleIncrement= () => {this.setState(state => {value: state.value + 1 });
};
handleDecrement= () => {this.setState(state => {value: state.value - 1 });
};
render() {return (<div><h2>{this.state.value}</h2><button onClick={this.handleDecrement}>Decrement</button><button onClick={this.handleIncrement}>Increment</button></div>);
}
};

We updated the state by calling setState in each of the functions handling a button click. The counter displayed on the page will update in real time. Thus, React gets its name because it reacts to state changes.

我们通过在处理按钮单击的每个函数中调用setState来更新状态。 页面上显示的计数器将实时更新。 因此,React之所以得名,是因为它对状态变化做出React

In short, React automatically monitors every component state for changes and updates the DOM appropriately.

简而言之,React自动监视每个组件状态的更改并适当地更新DOM。

道具 (Props)

We can use props (short for "properties") to allow components to talk to each other.

我们可以使用props(“属性”的缩写)来允许组件相互通信。

Suppose the counter in our previous example represents the quantity of a product a customer wishes to purchase. The store wants to place a limit of 2 products purchased per customer. At checkout, we want to display an appropriate message if the customer tries to purchase more than 2.

假设我们前面的示例中的计数器代表客户希望购买的产品数量。 商店希望限制每个客户购买2件产品。 结帐时,如果客户尝试购买2个以上的商品,我们希望显示一条适当的消息。

Here’s how we may do it with props:

这是我们可以通过道具完成的方法:

const Display = (props) => {let message;if(props.number>2){message = ‘You’re limited to purchasing 2 max!’;}else{message = ‘All’s good.’;}return(<p>message</p>);
};class Timer extends React.Component {state = {quantity: 0}//...code for handling button clicking, updating state, etc.render(){return(<Display number = {this.state.quantity} />//...code for other components);}
};

We create a functional component called Display and pass props as a parameter. When we render this component, we pass to it number as an attribute set to the quantity of the product a customer wants to purchase. This is similar to setting an attribute of an HTML tag. We call this value with props.number in Display to determine what message to return.

我们创建一个称为Display的功能组件,并将props作为参数传递。 渲染此组件时,我们将传递给它的数字作为属性设置为客户要购买的产品数量。 这类似于设置HTML标签的属性。 我们在Display中用props.number调用此值,以确定要返回的消息。

组件生命周期 (Component Lifecycle)

As React updates the DOM based on component states, special methods called lifecycle methods exist to provide opportunities to perform actions at specific points in the lifecycle of a component.

当React根据组件状态更新DOM时,存在称为生命周期方法的特殊方法,以提供机会在组件生命周期的特定点执行操作。

They allow you to catch components at a certain point in time to call appropriate functions. These points of time can be before components are rendered, after they are updated, etc. You may want to explore a component’s lifecycle methods.

它们使您可以在某个时间点捕获组件以调用适当的功能。 这些时间点可以在渲染组件之前,更新组件之后等等。您可能想要探索组件的生命周期方法 。

To see lifecycle methods in action, you can check out this Pomodoro Clock I made.

要查看实际的生命周期方法,您可以查看我制作的Pomodoro Clock 。

The clock timer is initially set to the session length. When the session timer counts down to zero, the timer needs to switch to the break length and start counting down from there.

时钟计时器最初设置为会话长度。 当会话计时器递减计数到零时,计时器需要切换到中断长度并从此处开始递减计数。

Since the timer is a component, I used the lifecycle method componentDidUpdate within my main class component to handle any changes with handleChange():

由于定时器是一个组件,我使用了生命周期方法componentDidUpdate我的主类部件内来处理与任何更改handleChange()

componentDidUpdate() {this.handleChange();
}

You can think of lifecycle methods as adding event listeners in vanilla JS to a React component.

您可以将生命周期方法视为将原始JS中的事件侦听器添加到React组件。

你可以用React构建什么? (What Can You Build with React?)

So now you have a basic understanding of React, what can you build with it?

所以现在您对React有一个基本的了解,您可以用它来构建什么?

We already mentioned in the beginning of this post that Facebook developed React in 2011, so naturally the Facebook platform is based on React. Other famous apps that either completely or partially use React include Instagram, Netflix, and Whatsapp.

我们已经在本文的开头提到了Facebook在2011年开发了React,因此Facebook平台自然是基于React的。 其他完全或部分使用React的著名应用包括Instagram,Netflix和Whatsapp。

But as beginners of React, we are not looking to immediately build the next Facebook so here’s a list of 10 React Starter Project Ideas to Get You Coding.

但是作为React的初学者,我们不希望立即构建下一个Facebook,因此这里列出了10个React Starter项目创意来帮助您编码 。

If you want to learn more about web development and check out some examples of beginner-friendly React projects, visit my blog at 1000 Mile World.

如果您想了解有关Web开发的更多信息并查看一些适合初学者使用的React项目的示例,请访问我的博客1000 Mile World 。

Thanks for reading and happy coding!

感谢您的阅读和愉快的编码!

翻译自: https://www.freecodecamp.org/news/learn-react-basics-in-10-minutes/

react学习预备知识

react学习预备知识_在10分钟内学习React基础知识相关推荐

  1. iis 网站添加 身份验证_在10分钟内将身份验证添加到任何网页

    iis 网站添加 身份验证 This content is sponsored via Syndicate Ads 该内容是通过辛迪加广告 赞助的 Adding authentication to w ...

  2. 语音库构建_在10分钟内构建一个多功能语音助手

    语音库构建 Nowadays people don't have time to manually search the internet for information or the answers ...

  3. 网页视频15分钟自动暂停_在15分钟内学习网页爬取

    网页视频15分钟自动暂停 什么是网页抓取? (What is Web Scraping?) Web scraping, also known as web data extraction, is th ...

  4. bootstrap快速入门_在5分钟内学习Bootstrap 4-快速入门指南

    bootstrap快速入门 了解世界上最受欢迎的前端组件库的最新版本. (Get to know the newest version of the worlds most popular front ...

  5. java笔试必考知识_面试必备:常考Java基础知识总结(持续更新)

    本文的Java方面基础知识是我在面试过程中的积累和总结. Java基本数据类型.所占空间大小及对应包装类 基本类型 大小 包装类 boolean - Boolean char 16-bit Chara ...

  6. 深度学习所需显存_只需10分钟即可学习基本的Flexbox

    深度学习所需显存 by Justin Yek 贾斯汀·耶克(Justin Yek) 只需10分钟即可学习基本的Flexbox (Learn basic Flexbox in just 10 minut ...

  7. 【工具篇】10分钟快速学会React图表搭建

    10分钟快速学会React图表搭建 本次紧着之前的antd,接着学习有关react图表以及富文本编辑器的搭建. 本次的功能实现基于上次的[工具篇]10分钟学会Ant Design of React用法 ...

  8. 以太坊区块链同步_以太坊69:如何在10分钟内建立完全同步的区块链节点

    以太坊区块链同步 by Lukas Lukac 卢卡斯·卢卡奇(Lukas Lukac) Ethereu M 69:如何在10分钟内建立完全同步的区块链节点 (Ethereum 69: how to ...

  9. github创建静态页面_如何在10分钟内使用GitHub Pages创建免费的静态站点

    github创建静态页面 Static sites have become all the rage, and with good reason – they are blazingly fast a ...

最新文章

  1. 仿Gin搭建自己的web框架(五)
  2. 学习进度条(第六周)
  3. android toast有焦点,android – 如何在显示Toast后进行edittext自动对焦?
  4. 第一次听人用男女关系讲 N(Non-Blocking)I(进)O(出),涨姿势了
  5. jquery(js) 增加 删除 修改属性样式、元素内容
  6. C++中set按降序排序
  7. ajax 跨站返回值,jquery ajax 跨域问题
  8. 【2015蓝桥杯省赛】C++ B组试题
  9. anaconda的虚拟环境中查看已经安装好的包
  10. 容器使用的12条军规——《Effective+STL中文版》试读
  11. 【算法】排序_堆排序
  12. Matlab求整数规划
  13. openpyxl进行excel的整行复制
  14. android原生坐标系,经纬度查寻地图位置,坐标系在线互转
  15. excel 隔行插入和错位
  16. 学生计算机屏幕坏了怎么办,电脑自己检查自己修,如果显示器坏掉我们该怎么办?...
  17. 湖南广电台长吕焕斌:湖南电视台的新媒体发展战略
  18. 游戏开发高度图有关资料与Balder中的相关支持
  19. 用 Python 实现股票指数移动平均线
  20. 【EtherCAT分析】一、EtherCAT从站硬件分析

热门文章

  1. 题库明细 使用java理解程序逻辑
  2. dj鲜生-08-用户注册的功能-上-实现注册的主逻辑和其本的验证功能-伴随着调试
  3. linux-centos连网
  4. 算法--库函数实现全排列
  5. 云时代企业如何保护共享文档数据安全?
  6. Spring Bean的生命周期(非常详细)
  7. Spring-boot配置JedisShardInfo
  8. mysql增量备份及恢复解决方案
  9. Gmuplolader1.0正式上线,欢迎试用!!!
  10. 简析LIVE555中的延时队列