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

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学习预备知识

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值