react 最佳實踐
React is a JavaScript library for building user interfaces. It was voted the most loved in the “Frameworks, Libraries, and Other Technologies” category of Stack Overflow’s 2017 Developer Survey.
React是一個用于構建用戶界面JavaScript庫。 在Stack Overflow的2017年開發人員調查的“框架,庫和其他技術”類別中,它被評為最受關注的。
React is a JavaScript library and React applications built on it run in the browser, NOT on the server. Applications of this kind only communicate with the server when necessary, which makes them very fast compared to traditional websites that force the user to wait for the server to re-render entire pages and send them to the browser.
React是一個JavaScript庫,基于它的React應用程序在瀏覽器中運行,而不是在服務器上運行。 這種類型的應用程序僅在必要時與服務器通信,與傳統網站相比,傳統應用程序迫使用戶等待服務器重新呈現整個頁面并將其發送到瀏覽器,因此它們的速度非常快。
React is used for building user interfaces - what the user sees on their screen and interacts with to use your web app. This interface is split up into components, instead of having one huge page you break it up into smaller pieces known as components. In more general terms, this approach is called Modularity.
React用于構建用戶界面-用戶在屏幕上看到并與之交互以使用您的Web應用程序。 該界面分為多個組件,而不是擁有一個巨大的頁面,而是將其分解為稱為組件的較小部分。 更籠統地說,這種方法稱為模塊化。
- It’s declarative: React uses a declarative paradigm that makes it easier to reason about your application. 它是聲明性的:React使用聲明性范式,可以更輕松地推理您的應用程序。
- It’s efficient: React computes the minimal set of changes necessary to keep your DOM up-to-date. 高效:React計算出使DOM保持最新狀態所需的最小更改集。
- And it’s flexible: React works with the libraries and frameworks that you already know. 而且它很靈活:React可與您已經知道的庫和框架一起使用。
學習React的最佳教程 (The Best Tutorials for Learning React)
freeCodeCamp has a React tutorial on YouTube that will teach you all the basics in just 5 hours.
freeCodeCamp 在YouTube上有一個React教程,該教程將在5小時內教您所有基本知識。
We also have a more in-depth intermediate React tutorial that teaches you how to build an entire social media React app using Firebase. It is 12 hours long, and if you follow along, you will learn a ton of the intricacies of React.
我們還有一個更深入的中級React教程 ,教您如何使用Firebase構建整個社交媒體React應用。 它長達12個小時,如果您繼續學習,您將學到很多React的復雜知識。
為什么要學習React? (Why learn React?)
React involves Composition, that is lots of components wrapping up the functionalities into an encapsulated container.
React涉及成分,即許多將功能包裝到封裝容器中的組件。
Many popular websites use React implementing the MVC architectural pattern. Facebook (Partially), Instagram (Completely), Khan Academy (Partially), New York Times (Partially), Yahoo Mail (Completely), Dropbox’s new photo and video gallery app Carousel (Completely) are the popular websites known to be using React.
許多流行的網站都使用React實現MVC架構模式。 Facebook(部分),Instagram(完全),Khan Academy(部分),紐約時報(部分),Yahoo Mail(完全),Dropbox的新照片和視頻畫廊應用程序Carousel(完全)是眾所周知的使用React的流行網站。
How are these large applications built using React? The simple answer is by building small applications or components. Example:
如何使用React構建這些大型應用程序? 簡單的答案是通過構建小型應用程序或組件。 例:
const Component2 = () => {return (<div></div>);
};
const Component3 = () => {return (<div></div>);
};
const Component1 = () => {return (<div><Component2 /><Component3 /></div>);
};ReactDOM.render(<Component1 />, document.getElementById("app")
);
React is Declarative, for the most part, which means we are concerned more with what to do rather than how to do a specific task.
在大多數情況下,React是聲明式的,這意味著我們更關注要做什么而不是如何執行特定任務。
Declarative programming is a programming paradigm that expresses the logic of a computation without describing its control flow. Declarative programming comes with certain advantages such as reduced side effects (occurs when we modify any state or mutate something or make an API request), minimized mutability (as a lot of it is abstracted), enhanced readability, and fewer bugs.
聲明式編程是一種編程范例,用于表達計算的邏輯而不描述其控制流程。 聲明式編程具有某些優點,例如,減少了副作用(在我們修改任何狀態或進行某種更改或發出API請求時發生),最小化了可變性(因為很多抽象性),增強的可讀性和更少的錯誤。
React also has an unidirectional dataflow. UI in React is actually the function of the state. This means that as the state updates it updates the UI as well. So our UI progresses as the state changes.
React也有一個單向數據流。 React中的UI實際上是狀態的功能。 這意味著狀態更新時,UI也隨之更新。 因此,我們的UI隨著狀態的變化而發展。
React的優勢 (Advantages of React)
Some reasons to use React are:
使用React的一些原因是:
- Fast. Apps made in React can handle complex updates and still feel quick and responsive. 快速。 使用React制作的應用程序可以處理復雜的更新,并且仍然感覺快速且響應Swift。
Modular. Instead of writing large, dense files of code, you can write many smaller, reusable files. React’s modularity can be a beautiful solution to JavaScript’s maintainability problems.
模塊化。 您可以編寫許多較小的可重用文件,而不是編寫大型的密集代碼文件。 React的模塊化可以很好地解決JavaScript的可維護性問題 。
- Scalable. Large programs that display a lot of changing data are where React performs best. 可擴展 顯示大量變化數據的大型程序是React表現最好的地方。
Flexible. You can use React for interesting projects that have nothing to do with making a web app. People are still figuring out React’s potential. There’s room to explore.
靈活。 您可以將React用于與制作Web應用程序無關的有趣項目。 人們仍在挖掘React的潛力。 有探索的空間 。
虛擬DOM (Virtual DOM)
React’s magic comes from its interpretation of the DOM and its strategy for creating UIs.
React的魔力來自于對DOM的解釋及其創建UI的策略。
React uses the Virtual DOM to render an HTML tree virtually first. Then, every time a state changes and we get a new HTML tree that needs to be taken to the browser’s DOM, instead of writing the whole new tree React will only write the difference between the new tree and the previous tree (since React has both trees in memory). This process is known as Tree Reconciliation.
React首先使用Virtual DOM渲染HTML樹。 然后,每次狀態改變時,我們都會得到一個需要帶到瀏覽器DOM的新HTML樹,而不是編寫整個新樹,React只會寫出新樹和前一棵樹之間的差異(因為React既有樹又有樹)內存中的樹)。 此過程稱為“樹協調”。
和解 (Reconciliation)
React has a smart diffing algorithm that it uses to only regenerate in its DOM node what actually needs to be regenerated while it keeps everything else as is. This diffing process is possible because of React’s virtual DOM.
React有一個智能差異算法,它僅用于在其DOM節點中重新生成實際需要重新生成的內容,同時將其他所有內容保持不變。 由于React的虛擬DOM,這種差異化過程是可能的。
Using the virtual DOM, React keeps the last DOM version in memory. When it has a new DOM version to take to the browser, that new DOM version will also be in memory, so React can compute the difference between the new and the old versions.
使用虛擬DOM,React將最后的DOM版本保留在內存中。 當它具有要用于瀏覽器的新DOM版本時,該新DOM版本也會存儲在內存中,因此React可以計算新版本和舊版本之間的差異。
React will then instruct the browser to update only the computed diff and not the whole DOM node. No matter how many times we regenerate our interface, React will take to the browser only the new “partial” updates.
然后,React將指示瀏覽器僅更新計算的差異,而不更新整個DOM節點。 無論我們重新生成界面多少次,React都只會將新的“部分”更新帶給瀏覽器。
從頭開始React (React from Scratch)
Would you like to get started learning the basics of react without getting bogged down creating a development environment? Chances are that if you are new to web development, setting up a development environment can leave you feeling a little intimidated when you are just trying to learn React.
您是否想開始學習React的基礎知識而又不陷入開發環境的困境? 如果您是Web開發的新手,則可能會發現,設置開發環境會讓您在嘗試學習React時感到有些害怕。
In this article we are going to look at how we can get started with React using only a text editor and a browser and nothing else.
在本文中,我們將研究如何僅使用文本編輯器和瀏覽器,而不使用其他任何東西來開始使用React。
1 —使用Emmet設置鍋爐代碼 (1?—?Set Up Boiler Plate Code with Emmet)
Let’s get started with step 1. We’ll begin with a file in our browser called “index.html”. We’ll begin with the boiler plate HTML code. For a quick start I recommend using Emmet with whatever text editor you have. On the first line, type in html:5
then press the shift key to get the code below. Or you can go ahead and copy and paste the code from below.
讓我們從步驟1開始。我們將從瀏覽器中名為“ index.html”的文件開始。 我們將從樣板HTML代碼開始。 為了快速入門,我建議將Emmet與您擁有的任何文本編輯器一起使用。 在第一行中,輸入html:5
然后按Shift鍵以獲取下面的代碼。 或者,您可以繼續從下面復制并粘貼代碼。
html:5
This will result in the following code:
這將導致以下代碼:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title>
</head>
<body></body>
</html>
We can fill in the title of “Time to React!”.
我們可以填寫“React時間!”的標題。
This content will not appear in your webpage. Anything in the head section of the HTML file will be meta data that our browser will user to interpret our code in the body section. This title is going to be what appears on the tab for our page, not actually on the page.
此內容不會出現在您的網頁中。 HTML文件開頭部分中的任何內容都是元數據,我們的瀏覽器將使用這些元數據來解釋主體部分中的代碼。 該標題將顯示在我們頁面的標簽上,而不是實際在頁面上。
2-獲取腳本標簽以利用React和Babel庫的功能 (2 - Get Script Tags to Harness the Power of React and Babel Libraries)
Ok, item one is checked off of our list. Let’s look at item two. We are going to set up our developer environment by using script tags to bring in React and Babel.
好的,第一項已從我們的清單中剔除。 讓我們看一下第二項。 我們將通過使用腳本標簽引入React和Babel來建立我們的開發人員環境。
This is not a real life developer environment. That would be quite an elaborate setup. It would also leave us with a lot of boiler plate code and libraries that would take us off subject of learning React basics. The goal of this series is to go over the basic syntax of React and get right into coding. We are going to use <script>
tags to bring in the React Library, the React DOM library (why), and the Babel library.
這不是現實生活中的開發人員環境。 那將是一個相當復雜的設置。 它還會給我們留下很多樣板代碼和庫,這會使我們脫離學習React基礎的主題。 本系列文章的目的是研究React的基本語法,并開始進行編碼。 我們將使用<script>
標簽引入React庫,React DOM庫(為什么)和Babel庫。
<head>...<!-- REACT LIBRARY --><script src="https://unpkg.com/react@15.5.4/dist/react.js"></script><!-- REACT DOM LIBRARY --><script src="https://unpkg.com/react-dom@15.5.4/dist/react-dom.js"></script><!-- BABEL LIBRARY --><script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.25.0/babel.min.js"></script>...<title>Time to React!</title>
</head>
You are free to use more updated versions of these libraries as they come out. They should not create any breaking changes for the content we are covering.
您可以隨意使用這些庫的更多更新版本。 他們不應為我們涵蓋的內容進行任何重大更改。
What are we doing here? The HTML <script>
element is used to embed or reference an executable script. The “src” attribute points to the external script files for the React library, ReactDOM library and Babel library.
我們在這里做什么? HTML <script>
元素用于嵌入或引用可執行腳本。 “ src”屬性指向React庫,ReactDOM庫和Babel庫的外部腳本文件。
This is like if you have an electric razor. It is literally no good to you no matter how fancy the electric razor unless you can plug it into the wall and gain access to electricity. Our React code we will write will be no good to us if our browser can’t plug into these libraries to understand and interpret what we are going.
這就像您有電動剃須刀一樣。 除非您將電動剃須刀插入墻上并獲得電力,否則無論電動剃須刀多么花哨,這對您實際上都是不利的。 如果我們的瀏覽器無法插入這些庫來理解和解釋我們要做什么,那么我們將要編寫的React代碼對我們不利。
This is how our application is going to gain the power of React, it is going to be how we insert React into the Dom. We have React and ReactDOM as two different libraries because there are use cases such as React Native where rendering to the DOM isn’t needed for mobile development so the library was split so people could decide what they needed depending on the project they were working on.
這就是我們的應用程序將如何獲得React的功能,這將是我們將React插入Dom的方式。 我們將React和ReactDOM作為兩個不同的庫,因為在某些情況下(例如React Native),移動開發不需要渲染到DOM,因此將庫拆分開了,以便人們可以根據自己從事的項目來決定需要什么。
Because we will need our React to make it to the DOM we’ll use both scripts. Babel is how we take advantage of ECMA script beyond ES5 and deal with something called JSX (JavaScript as XML) that we will use in React. We’ll take a deeper look at the magic of Babel in an upcoming section :)
因為我們將需要React使其成為DOM,所以我們將使用這兩個腳本。 Babel是我們如何利用ES5以外的ECMA腳本并處理將在React中使用的JSX(JavaScript作為XML)。 在下一部分中,我們將更深入地了解Babel的魔力:)
Alright, we have completed steps 1 and 2. We have set up our boiler plate code and set up our developer environment.
好了,我們已經完成了步驟1和2。已經設置了樣板代碼并設置了開發人員環境。
3-渲染對DOM的React (3 - Render React to the DOM)
Our next two steps will be to choose our location within the DOM that we want to render our React content. And we'll use another script tag for our React content within the body. Generally, as a good separations of concerns practice, this would be in its own file then linked to this html document. We’ll do that later in upcoming sections. For now, we’ll let this dwell within the body of the html document we are currently in.
接下來的兩個步驟將是選擇我們要呈現React內容的DOM中的位置。 我們將在正文中為我們的React內容使用另一個腳本標簽。 通常,作為關注點分離的良好做法,這將在其自己的文件中,然后鏈接到此html文檔。 我們將在以后的部分中進行介紹。 現在,我們將其保留在當前所在的html文檔的正文中。
Now we are going to look at how simple it is to choose a place on the DOM to render our React content. We’ll go within the body. And best practice isn’t just to throw React into the body tag to be displayed but to create a separate element, often a div, that you can treat as a root element to insert your React content.
現在我們來看看在DOM上選擇一個位置來呈現React內容有多么簡單。 我們將進入體內。 最佳實踐不僅是將React放入要顯示的body標簽中,還創建一個單獨的元素(通常是div),您可以將其視為插入React內容的根元素。
<body><div id="app">React has not rendered yet</div>
</body>
We’ll create a simple <div>
element and give it an id of “app”. We are going to be able to target this location to insert our React content much the same way you might use CSS to target an id for styling of your choice. Any react content will be rendered within the div tags with the id of app. In the meantime we’ll leave some text saying that “React has not rendered yet”. If we see this when we preview our page it means that somewhere we missed rendering React.
我們將創建一個簡單的<div>
元素,并將其ID設置為“ app”。 我們將能夠以這個位置為目標來插入我們的React內容,就像您可以使用CSS來為您選擇的樣式作為目標的id一樣。 任何React內容都將在div標簽中呈現,其ID為app。 同時,我們將保留一些文字,說明“React尚未呈現”。 如果在預覽頁面時看到此消息,則意味著我們錯過了渲染React的地方。
Now, let’s go ahead and create a script tag within our body where we will create with React for the first time. The syntax we are going to need for our script tag is to add an attribute of “type”. This specifies the media type of the script. Above in our head we used an src attribute that pointed to the external script files for the React library, ReactDOM library and Babel library.
現在,讓我們繼續在我們的體內創建腳本標簽,這是我們第一次使用React創建的標簽。 我們腳本標簽所需的語法是添加“ type”屬性。 這指定腳本的媒體類型。 在我們頭頂的上方,我們使用了src屬性,該屬性指向React庫,ReactDOM庫和Babel庫的外部腳本文件。
<body><div id="app">React has not rendered yet</div><script type="text/babel"></script>
</body>
The “type” of script that we are using will be wrapped in quotes and set to "text/babel"
. We’ll need the ability to use babel right away as we work with JSX.
我們正在使用的腳本的“類型”將用引號引起來,并設置為"text/babel"
。 與JSX一起使用時,我們需要立即使用babel的功能。
First, we are going to render React to the DOM. We will use the ReactDOM.render()
method to do this. This will be a method, and remember a method is just a function attached to an object. This method will take two arguments.
首先,我們將React渲染為DOM。 我們將使用ReactDOM.render()
方法執行此操作。 這將是一個方法,請記住,方法只是附加到對象的函數。 此方法將有兩個參數。
<body><div id="app">React has not rendered yet</div><script type="text/babel">ReactDOM.render(React What, React Where);
</script>
</body>
The first argument is the “what” of React. The second argument is the “where” of the location you want it to be placed in the DOM. Let’s start by calling our ReactDOM.render() method. Our first argument is going to be our JSX.
第一個參數是React的“內容”。 第二個參數是您希望將其放置在DOM中的位置的“位置”。 讓我們從調用ReactDOM.render()方法開始。 我們的第一個參數將是我們的JSX。
<body><div id="app">React has not rendered yet</div><script type="text/babel">ReactDOM.render(<h1>Hello World</h1>, React Where);
</script>
</body>
The official react docs state: “This funny tag syntax is neither a string nor HTML. It is called JSX, and it is a syntax extension to JavaScript. We recommend using it with React to describe what the UI should look like. JSX may remind you of a template language, but it comes with the full power of JavaScript. JSX produces React “elements.”
官方的react docs聲明 :“這種有趣的標記語法既不是字符串也不是HTML。 它稱為JSX,是JavaScript的語法擴展。 我們建議將它與React一起使用,以描述UI的外觀。 JSX可能會讓您想起模板語言,但是它具有JavaScript的全部功能。 JSX產生React“元素”。
Often times, JSX freaks people out who have been developers for a while because it looks like HTML. At a very early age developers are taught separation of concerns. HTML has its place, CSS has its place and JavaScript has its place. JSX seems to blur the lines. You are using what looks like HTML but as Facebook says it comes with the full power of JavaScript.
通常,JSX看起來很像HTML,因此經常使曾經從事過開發工作的人迷住了。 在很小的時候,開發人員就學會了關注點分離。 HTML有它的位置,CSS有它的位置,而JavaScript有它的位置。 JSX似乎模糊了界限。 您正在使用看起來像HTML的東西,但是正如Facebook所說的那樣,它具有JavaScript的全部功能。
This can freak out veterans, so many React tutorials start without JSX which can be quite complex. We won’t do that. Because this article is directed towards those who are very young in their careers you may not bring those red flags when you see this syntax.
這可能會讓退伍軍人大吃一驚,因此許多React教程開始時都沒有JSX,這可能非常復雜。 我們不會那樣做。 因為本文是針對那些職業生涯還很年輕的人,所以當您看到此語法時,可能不會帶上那些危險信號。
And JSX is just really intuitive. You can probably quite easily read this code and see that this is going to be the largest header tag displaying the text “Hello World”. No mystery and pretty straightforward. Now, let’s look at what our second argument would be.
JSX真的很直觀。 您可能很容易閱讀此代碼,并看到它將成為顯示文本“ Hello World”的最大標頭標記。 沒有神秘感,也很簡單。 現在,讓我們看看第二個參數是什么。
<body><div id="app">React has not rendered yet</div><script type="text/babel">ReactDOM.render(<h1>Hello World</h1>, document.getElementById("app"));</script>
</body>
This is where we want our React content rendered to the DOM. You’ve probably done this quite a few times in the past. We’ll just type in document.getElementById()
. And we’ll pass into the argument of the id of app. And that is it. We will now target the div with the id of app to insert our React content.
這是我們希望將React內容呈現到DOM的地方。 您過去可能已經做過幾次了。 我們只需要輸入document.getElementById()
。 我們將傳入app id的參數。 就是這樣。 現在,我們將使用app的id作為div來插入我們的React內容。
We want to make sure our content is saved. Go ahead and open this up in the browser and you should see “Hello World”. As you can probably guess, using React is not the quickest or best way to create a Hello World app. We aren’t quite seeing the benefits of it yet. But now, we know that everything is working.
我們要確保我們的內容已保存。 繼續并在瀏覽器中打開它,您應該看到“ Hello World”。 您可能會猜到,使用React并不是創建Hello World應用程序的最快或最佳方法。 我們還沒有看到它的好處。 但是現在,我們知道一切正常。
Go ahead and open up the console and look at the “elements”. You can do that on a Mac with command + shift + j or on Windows and Linux: Ctrl + Shift + J
繼續并打開控制臺,然后查看“元素”。 您可以在Mac上使用Command + shift + j或在Windows和Linux上執行此操作:Ctrl + Shift + J
If you click on the head tag, we can see our script libraries we included. Then we can go down to the body of our document. Let’s click on our div with the id of “app”. And when we do we see our <h1>
tag with the content “Hello World”.
如果單擊head標簽,我們可以看到包含的腳本庫。 然后我們可以進入文檔正文。 讓我們單擊ID為“ app”的div。 當我們這樣做時,我們會看到帶有內容“ Hello World”的<h1>
標簽。
View Entire Code Here.
在此處查看整個代碼 。
回顧 (Recap)
So let’s do a quick recap. In our head tag we grabbed the script tags for React, ReactDOM and Babel. These are the tools our browser needs in its meta data to read our React code and JSX in specific.
因此,讓我們快速回顧一下。 在我們的head標簽中,我們抓取了React,ReactDOM和Babel的腳本標簽。 這些是我們的瀏覽器在其元數據中讀取特定的React代碼和JSX所需的工具。
We then located the position within the DOM that we wanted to insert our React by creating an element div with the id of “app”.
然后,我們通過創建ID為“ app”的div元素來定位要插入React的DOM中的位置。
Next, we created a script tag to input our React code. We used the ReactDOM.render() method that takes two arguments. The “what” of the React content, in this case our JSX, and the second argument is the “where” that you want to insert the React content into the DOM. In this case it is the location with the id of “app”.
接下來,我們創建了一個腳本標簽來輸入我們的React代碼。 我們使用了帶有兩個參數的ReactDOM.render()方法。 React內容的“內容”(在本例中為我們的JSX),第二個參數是您要將React內容插入DOM的“位置”。 在這種情況下,它是ID為“ app”的位置。
As an alternative to JSX, you can use ES6 and Javascript’s compiler like Babel. https://babeljs.io/
作為JSX的替代,您可以使用ES6和Java的編譯器(如Babel)。 https://babeljs.io/
安裝React (Installing React)
創建一個新的React項目 (Creating a new React project)
You could just embed the React library in your webpage like so2:
您可以像這樣2將React庫嵌入到您的網頁中:
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/cjs/react.production.min.js"></script>
Smart programmers want to take the more practical and productive way: Create React App
聰明的程序員希望采取更實際,更高效的方式: 創建React App
npm install -g create-react-app
create-react-app my-appcd my-app
npm start
This will set up your development environment so that you can use the latest JavaScript features, provide a nice developer experience, and optimize your app for production.
這將設置您的開發環境,以便您可以使用最新JavaScript功能,提供良好的開發人員體驗以及優化應用程序以進行生產。
npm start
will start up a development server which allows live reloading3.
npm start
將啟動一個開發服務器,該服務器可以實時重新加載3 。
After you finish your project and are ready to deploy your App to production, you can just use npm run build
to create an optimized build of your app in the build
folder.
完成項目并準備將App部署到生產環境后,您可以使用npm run build
在build
文件夾中創建應用的優化版本。
您的第一個React App (Your first React App)
安裝 (Installation)
As specified in the previous section (Installation), run the Create React App
tool. After everything has finished, cd
into the folder of your application and run npm start
. This will start a development server and you are all set to start developing your app!
如上一節(安裝)中所述,運行Create React App
工具。 完成所有操作后,將cd
放入您的應用程序文件夾并運行npm start
。 這將啟動開發服務器,您已經準備好開始開發應用程序!
npm install -g react-create-app
create-react-app my-first-appcd my-first-app
npm start
編輯代碼 (Editing the code)
Start up your editor or IDE of choice and edit the App.js
file in the src
folder. When created with the react-create-app
tool, there will already be some code in this file.
啟動您選擇的編輯器或IDE,然后編輯src
文件夾中的App.js
文件。 當使用react-create-app
工具react-create-app
,該文件中已經有一些代碼。
The code will consist of these parts:
該代碼將包括以下部分:
進口 (imports)
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
This is used by webpack to import all required modules so that your code can use them. This code imports 3 modules:
webpack使用它導入所有必需的模塊,以便您的代碼可以使用它們。 此代碼導入3個模塊:
React
andComponent
, which allow us to use React as it should be used. (With components)React
和Component
,這使我們能夠使用應使用的React。 (帶組件)logo
, which allows us to uselogo.svg
in this file.logo
,這使我們可以在此文件中使用logo.svg
。./App.css
, which imports the stylesheet for this file../App.css
,它將為此文件導入樣式表。
類/組件 (classes/components)
class App extends Component {render() {return (<div className="App"><header className="App-header"><img src={logo} className="App-logo" alt="logo" /><h1 className="App-title">Welcome to React</h1></header><p className="App-intro">To get started, edit <code>src/App.js</code> and save to reload.</p></div>);}
}
React is a library that makes use of Components, which let you split up your UI into independent, reusable pieces, and think about each piece in isolation. There is already 1 component created, the App
component. If you used the create-react-app
tool, this component is the main component in the project and you should build around this central class.
React是一個利用組件的庫,它使您可以將UI分成獨立的,可重用的部分,并單獨考慮每個部分。 已經創建了1個組件,即App
組件。 如果您使用create-react-app
工具,則此組件是項目中的主要組件,您應該圍繞此中心類進行構建。
We will look at components in more detail shortly.
我們將在短期內更詳細地介紹組件。
出口商品 (exports)
When creating a class in React, you should export them after declaration, which allows you to use the component in another file by using the import
keyword. You can use default
after the export
keyword to tell React that this is the main class of this file.
在React中創建類時,應在聲明后導出它們,這允許您通過使用import
關鍵字在另一個文件中使用組件。 您可以在export
關鍵字之后使用default
來告訴React這是此文件的主類。
export default App;
查看結果! (View the results!)
When you’ve started the development server by issuing the npm start
command, you can view the changes you add to your project live in your browser. After issuing the command, npm should open a browser automatically displaying your app.
通過發出npm start
命令啟動開發服務器后,您可以在瀏覽器中實時查看添加到項目中的更改。 發出命令后,npm應打開自動顯示您的應用程序的瀏覽器。
React-組件 (React - Components)
Components are reusable in React. You can inject value into props as given below:
組件可在React中重用。 您可以如下所示將值注入道具:
function Welcome(props) {return <h1>Hello, {props.name}</h1>;
}const element = <Welcome name="Faisal Arkan" />;
ReactDOM.render(element,document.getElementById('root')
);
name="Faisal Arkan"
will give value into {props.name}
from the ?function Welcome(props)
and will return the component that has given value by name="Faisal Arkan"
. After that react will render the element into HTML.
name="Faisal Arkan"
將通過function Welcome(props)
將值{props.name}
,并返回具有name="Faisal Arkan"
值的組件。 之后,react將把元素渲染為HTML。
聲明組件的其他方式 (Other ways to declare components)
There are many ways to declare components when using React. There are two kinds of components, stateless components and stateful components.
使用React時有很多方法來聲明組件。 組件有兩種, 無狀態組件和有狀態組件。
有狀態的 (Stateful)
類類型組件 (Class Type Components)
class Cat extends React.Component {constructor(props) {super(props);this.state = {humor: 'happy'}}render() {return(<div><h1>{this.props.name}</h1><p>{this.props.color}</p></div>);}
}
無狀態組件 (Stateless Components)
功能組件(ES6中的箭頭功能) (Functional Components (Arrow Function from ES6))
const Cat = props => {return ( <div><h1>{props.name}</h1><p>{props.color}</p></div>;);
};
隱式返回組件 (Implicit Return Components)
const Cat = props => <div><h1>{props.name}</h1><p>{props.color}</p></div>;
翻譯自: https://www.freecodecamp.org/news/best-react-javascript-tutorial/
react 最佳實踐