reactjs快速如夢
此帖子分為2部分 (This Post is divided into 2 parts)
- The First Part demonstrates how to create a simple React app using ‘create-react-app’ CLI and explains the project structure. 第一部分演示了如何使用“ create-react-app” CLI創建簡單的React應用,并說明了項目結構。
- The Second Part explains an existing code that I have posted in Github. This code demonstrates the use of components, communication between components, making HTTP calls and React Bootstrap (bootstrap which is written for React). 第二部分介紹了我在Github中發布的現有代碼。 該代碼演示了組件的使用,組件之間的通信,進行HTTP調用以及React Bootstrap(為React編寫的Bootstrap)。
第1部分 (Part 1)
如果尚未安裝NodeJS,請安裝 (Install NodeJS if not already present)
NodeJS is needed since the Libraries Required for React are downloaded using node package manager ( npm ). Refer to https://nodejs.org/en/ to install NodeJS.
需要NodeJS,因為使用節點包管理器(npm)下載了React所需的庫。 請參閱https://nodejs.org/en/安裝NodeJS。
安裝create-react-app節點軟件包 (Install create-react-app Node Package)
create-react-app node package helps to set up a React project. Install create-react-app node package globally using the following command.
create-react-app節點包有助于建立一個React項目。 使用以下命令全局安裝create-react-app節點程序包。
npm install -g create-react-app
創建項目 (Create The Project)
The project can be created using create-react-app. Use the following command to create the project.
可以使用create-react-app創建項目。 使用以下命令創建項目。
npx create-react-app first-react-app
first-react-app is the name of the application. The above command creates a folder called first-react-app which is the project folder. In order to test if everything has been set up properly, go into the project folder and start the application using the following command.
first-react-app是應用程序的名稱。 上面的命令創建一個名為first-react-app的文件夾,它是項目文件夾。 為了測試是否一切都已正確設置,請進入項目文件夾并使用以下命令啟動應用程序。
cd first-react-app
npm start
Go to your browser and go the following URL localhost:3000You should be able to see that your application is running. The Application will look like this in your browser:
轉到瀏覽器并轉到以下URL localhost:3000,您應該能夠看到您的應用程序正在運行。 該應用程序在您的瀏覽器中將如下所示:
基本文件夾結構介紹 (Basic Folder Structure Explained)
When you created the project, you would have noticed that it created a bunch of files. Here I will list out some of the important files and folders that you should be aware of .
創建項目時,您會注意到它創建了許多文件。 在這里,我將列出您應該注意的一些重要文件和文件夾。
package.json: This File has the list of node dependencies which are needed.
package.json:此文件包含所需的節點依賴項列表。
public/index.html: When the application starts this is the first page that is loaded. This will be the only html file in the entire application since React is generally Written using JSX which I will cover later. Also, this file has a line of code <div id=”root”></div>. This line is very significant since all the application components are loaded into this div.
public / index.html:應用程序啟動時,這是加載的第一頁。 這是整個應用程序中唯一的html文件,因為React通常是使用JSX編寫的,我將在稍后介紹。 此外,該文件還有一行代碼<div id =” root”> </ div> 。 這條線是非常顯著,因為所有的應用組件loade d扎成這個div。
src/index.js: This is the javascript file corresponding to index.html. This file has the following line of code which is very significant. ReactDOM.render(<App />, document.getElementById(‘root’));
src / index.js :這是與index.html對應的javascript文件。 該文件包含以下非常重要的代碼行。 ReactDOM.render(<App />,document.getElementById('root'));
The above line of code is telling that App Component ( will cover App Component soon) has to be loaded into an html element with id root. This is nothing but the div element present in index.html.
上面的代碼行告訴我們,必須將App Component(即將覆蓋App Component)加載到id為root的html元素中。 這只是index.html中存在的div元素 。
src/index.css: The CSS file corresponding to index.js.
src / index.css :與index.js對應CSS文件。
src/App.js : This is the file for App Component. App Component is the main component in React which acts as a container for all other components.
src / App.js :這是應用組件的文件。 App Component是React中的主要組件,它充當所有其他組件的容器。
src/App.css : This is the CSS file corresponding to App Component
src / App.css :這是與應用程序組件相對應CSS文件
build: This is the folder where the built files are stored. React Apps can be developed using either JSX, or normal JavaScript itself, but using JSX definitely makes things easier to code for the developer :). But browsers do not understand JSX. So JSX needs to be converted into javascript before deploying. These converted files are stored in the build folder after bundling and minification. In order to see the build folder Run the following command
build:這是存儲構建文件的文件夾。 可以使用JSX或常規JavaScript本身來開發React Apps,但是使用JSX無疑使開發人員更容易編寫代碼:)。 但是瀏覽器不了解JSX。 因此,在部署之前,需要將JSX轉換為javascript。 捆綁和縮小后,這些轉換后的文件將存儲在build文件夾中。 為了查看構建文件夾,請運行以下命令
npm run build
創建組件 (Creating Components)
A Component in React does a specific functionality. An Application is nothing but a collection of components. Each component can have multiple child components and the components can communicate with each other.
React中的組件具有特定功能。 應用程序不過是組件的集合。 每個組件可以具有多個子組件,并且這些組件可以相互通信。
Let's create a React Component now.
現在創建一個React組件。
Inside src folder create a file called as FirstComponent.js and copy the following code into FirstComponent.js.
在src文件夾中,創建一個名為FirstComponent.js的文件,并將以下代碼復制到FirstComponent.js中。
import React, {Component} from 'react';export default class FirstComponent extends Component {constructor(props) {super(props)}render() {const element = (<div>Text from Element</div>)return (<div className="comptext"><h3>First Component</h3>{this.props.displaytext}{element}</div>)}
}
The Component name is FirstComponent which is denoted by the file name as well as in the statement
export default class FirstComponent extends Component
組件名稱是FirstComponent ,它由文件名以及在語句
export default class FirstComponent extends Component
The props attribute in the constructor will contain all the parameters which are passed as input to this component.
構造函數中的props屬性將包含所有作為輸入傳遞到此組件的參數。
render(): The return value of this function is rendered ( displayed ) on the screen. Whenever the render() function is called the Screen is rerendered. This is generally done automatically by the application. The code which looks very similar to html in this function is nothing but JSX.
render():此函數的返回值在屏幕上呈現(顯示)。 每當調用render()函數時,都會重新渲染屏幕。 通常,這是由應用程序自動完成的。 在此函數中看起來與html非常相似的代碼不過是JSX。
JSX (JSX)
JSX looks very similar to HTML but has the full power of javascript. Here I will Explain the JSX code and what it is trying to do.
JSX看起來非常類似于HTML,但是具有javascript的全部功能。 在這里,我將解釋JSX代碼及其作用。
render() {const element = (<div>Text from Element</div>)return (<div className="comptext"><h3>First Component</h3>{this.props.displaytext}{element}</div>)}
The first line const element = (<div>Text from Element</div>)
Creates a div element and assigns it to a constant called element. This peculiar Syntax that you see is nothing but JSX.
第一行const element = (<div>Text from Element</div>)
創建一個div元素,并將其分配給一個稱為element的常量。 這種奇特的語法,你看到的是荷蘭國際集團使者諾斯但JSX。
Inside the Return statement, you see the following code syntax.
在Return語句內,您將看到以下代碼語法。
<div className="comptext"><h3>First Component</h3>{this.props.displaytext}{element}
</div>
Here className is used to point to a CSS class. <h3>First Component</h3>
is just normal html Syntax. {this.props.displaytext}
is used to access an attribute called as displaytext from props ( so displaytext is passed as an input whenever this component is called ). Here displaytext is just a custom name that I have Given. {element}
is the constant which was created, which in turn contains the div element.
在這里, className用于指向CSS類。 <h3>First Component</h3>
只是普通的html語法。 {this.props.displaytext}
用于訪問來自props的稱為displaytext的屬性(因此,只要調用此組件, {this.props.displaytext}
displaytext作為輸入傳遞)。 這里displaytext只是我給定的一個自定義名稱。 {element}
是創建的常量,而常量又包含div元素。
使用組件 (Using the Component)
FirstComponent has been created but is not being used anywhere yet. Let's add FirstComponent to App Component. Here is the modified code for App.js
FirstComponent已創建,但尚未在任何地方使用。 讓我們將FirstComponent添加到App Component中。 這是App.js的修改后的代碼
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import FirstComponent from './FirstComponent'
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><FirstComponent displaytext="First Component Data"/></div>
);}
}
export default App;
FirstComponent needs to be imported into App Component First which is done in the line import FirstComponent from ‘./FirstComponent’
首先需要將FirstComponent導入到App Component First中,這是import FirstComponent from './FirstComponent'
中的import FirstComponent from './FirstComponent'
行中完成import FirstComponent from './FirstComponent'
Then FirstComponent is added to App Component using the line <FirstComponent displaytext=”First Component Data”/>
然后使用<FirstComponent displaytext=”First Component Data”/>
行將FirstComponent添加到App Component。
Here displaytext is passed as an attribute to the FirstComponent.
這里displaytext作為屬性傳遞給FirstComponent。
Now you can run the Application using the command npm start
現在,您可以使用命令npm start
運行該應用npm start
You should see the following result in the browser.
您應該在瀏覽器中看到以下結果。
恭喜😄 (Congrats😄)
Now you know how to create a React Application and how to create and use React Components. You also know a bit about JSX :)
現在您知道了如何創建React應用程序以及如何創建和使用React組件。 您也對JSX有所了解:)
The next part will explain an existing React Code from Github. Part 2 code is different from the code that we wrote in Part 1.
下一部分將解釋來自Github的現有React Code。 第2部分的代碼與第1部分中編寫的代碼不同。
第2部分 (Part 2)
碼 (Code)
The Following Code is being explained here so clone the repo into your computer. The Repo has instructions on how to clone and set up the code in your computer.
此處說明了以下代碼,因此請將存儲庫克隆到您的計算機中。 存儲庫包含有關如何在計算機中克隆和設置代碼的說明。
https://github.com/aditya-sridhar/simple-reactjs-app (https://github.com/aditya-sridhar/simple-reactjs-app)
申請網址 (Application URL)
To see how the final Application looks like you can click on the following URL. This will give a good idea as to what the Application is trying to do
要查看最終應用程序的外觀,可以單擊以下URL。 這樣可以很好地了解應用程序正在嘗試做什么
https://aditya-sridhar.github.io/simple-reactjs-app (https://aditya-sridhar.github.io/simple-reactjs-app)
The Application would look like this in a mobile screen
該應用程序在移動屏幕上看起來像這樣
該應用程序做什么 (What does this Application do)
This application displays a list of customers. When a customer is selected, it displays the details of the selected customer. This is a Single Page Application (SPA). React is best suited for Single Page Applications. Single Page Applications display everything within a single page.
該應用程序顯示客戶列表。 選擇客戶后,它將顯示所選客戶的詳細信息。 這是一個單頁應用程序(SPA)。 React最適合單頁應用程序 。 單頁應用程序顯示單個頁面中的所有內容。
申請結構說明 (Application Structure Explained)
客戶組成 (Customers Component)
This Component displays the list of Customers. This corresponds to the file src/Customers.js . This component has the following constructor.
該組件顯示客戶列表。 這對應于文件src / Customers.js 。 該組件具有以下構造函數。
constructor(props) {super(props)this.state = {selectedCustomer: 1}
}
props were already explained. But here you also see this.state. Whenever state changes, the component is rerendered. Here state has one parameter called selectedCustomer which is to keep track of which customer is selected. If selectedCustomer changes then the component and its child components are rerendered. The Constructor is used only to set props and state. Also, props should never be edited inside a component.
道具已經解釋過了。 但是在這里您也可以看到this.state 。 每當狀態更改時,都會重新呈現組件。 這里狀態有一個稱為selectedCustomer的參數,用于跟蹤選擇了哪個客戶。 如果selectedCustomer更改,則將重新呈現組件及其子組件 。 構造函數僅用于設置道具和狀態。 同樣, 道具 絕不能在組件內部進行編輯 。
The next thing you notice is the following code.
您注意到的下一件事是以下代碼。
componentDidMount() {this.getCustomerData();
}
componentDidMount() is a function which is called as soon the component is rendered. So this can be used to set some initial values as well as load data. Here it is calling a function called as getCustomerData()
componentDidMount()是一個函數,將在呈現組件后立即調用它。 因此,可用于設置一些初始值以及加載數據。 在這里它調用了名為getCustomerData()的函數
The next piece of code that you see is
您看到的下一段代碼是
getCustomerData() {axios.get('assets/samplejson/customerlist.json').then(response => {this.setState({customerList: response})})
};
This function getCustomerData() makes an HTTP call to read the sample json containing the list of customers from assets/samplejson/customerlist.json. On successfully getting a response, the state of the system is changed, by assigning the response to customerList. You may wonder why we never added customerList in the constructor. The reason is you can add parameters dynamically into State at any point in the code. The only requirement is that in the constructor at least an empty state has to be defined.
此函數getCustomerData()進行HTTP調用,以從資產/samplejson/customerlist.json中讀取包含客戶列表的示例json 。 成功獲得響應后,通過將響應分配給customerList來更改系統狀態。 您可能想知道為什么我們從未在構造函數中添加customerList。 原因是您可以在代碼中的任何位置將參數動態添加到State中。 唯一的要求是在構造函數中至少必須定義一個空狀態。
Here axios library is used to make the HTTP call. I have provided the Documentation for axios in the References section.
在這里, axios庫用于進行HTTP調用。 我在“參考”部分中提供了axios的文檔。
The next function is the render() function which returns what elements have to be rendered on screen. The main points of focus in the render function are
下一個函數是render()函數,該函數返回必須在屏幕上呈現的元素。 渲染功能的主要重點是
<Button bsStyle="info" onClick={() => this.setState({selectedCustomer: customer.id})}>Click to View Details</Button>
Every customer in the list has a button called as Click to View Details. The above code snippet tells that whenever the button is clicked, then change the state of selectedCustomer to the selected customers' id. Since the state changes here, the component and its child component will be rerendered.
列表中的每個客戶都有一個名為“ 單擊以查看詳細信息”的按鈕。 上面的代碼片斷告訴每當按鈕被點擊,然后selectedCustomer的狀態改變到所選擇的客戶的ID。 由于狀態在此處更改,因此將重新呈現組件及其子組件。
The other code snippet which is important is
另一個重要的代碼段是
<CustomerDetails val={this.state.selectedCustomer}/>
This snippet tells that CustomerDetails is a child component of Customers component and also passes the selectedCustomer id as an input to CustomerDetails component
此代碼段表明CustomerDetails是Customers組件的子組件,并且還將selectedCustomer id作為輸入傳遞給CustomerDetails組件
客戶詳細信息組件 (CustomerDetails Component)
This component displays the details of the selected Customer. Some important code snippets from this component will be explained here:
此組件顯示所選客戶的詳細信息。 這里將解釋該組件的一些重要代碼片段:
componentDidUpdate(prevProps) {//get Customer Details only if props has changed
//(props is the input) if (this.props.val !== prevProps.val) {this.getCustomerDetails(this.props.val)}
}
componentDidUpdate() function is called whenever the component is rerendered. Here we are calling getCustomerDetails() Function if the input to this component has changed when the component rerendered. The input passed to getCustomerDetails() function is this.props.val. this.props.val in turn, gets its value from Customers Component( selectedCustomer was passed as an input to this ). To know if the input has changed, the code snippet used is this.props.val !== prevProps.val
每當重新呈現組件時,都會調用componentDidUpdate()函數。 如果重新渲染組件時此組件的輸入已更改,則在此調用getCustomerDetails()函數。 傳遞給getCustomerDetails()函數的輸入是this.props.val 。 this.props.val依次從客戶組件獲取其值(selectedCustomer作為對此this的輸入傳遞)。 要知道輸入是否已更改,使用的代碼段是this.props.val !== prevProps.val
getCustomerDetails(id) {axios.get('assets/samplejson/customer' + id + '.json').then(response => {this.setState({customerDetails: response})})
};
getCustomerDetails() function makes an HTTP call to get the sample json which contains the customer details. The id parameter is used to know which customers details are required. id is nothing but this.props.val. When the response is successfully received the state of this component is changed by assigning response to customerDetails.
getCustomerDetails()函數進行HTTP調用以獲取包含客戶詳細信息的示例json。 id參數用于了解需要哪些客戶詳細信息。 id就是this.props.val。 成功接收到響應后,可以通過將響應分配給customerDetails來更改此組件的狀態。
The render() function for this component is pretty straightforward and simple so will not be covering that here
該組件的render()函數非常簡單明了,因此這里不再贅述
參考文獻 (References)
create-react-app: Refer to https://github.com/facebook/create-react-app to learn what all can be done using create-react-app
create-react-app:請參閱https://github.com/facebook/create-react-app以了解使用create-react-app可以完成的所有操作
ReactJS: Refer to https://reactjs.org/ to understand the concepts of ReactJS. The documentation is very good.
ReactJS:請參閱https://reactjs.org/以了解ReactJS的概念。 該文檔非常好。
React Bootstrap: Refer to https://react-bootstrap.github.io/getting-started/introduction/ to understand how to use React Bootstrap
React Bootstrap:參考https://react-bootstrap.github.io/getting-started/introduction/了解如何使用React Bootstrap
axios: Refer to https://www.npmjs.com/package/axios to know more about how to use axios library to make HTTP requests
axios:請訪問https://www.npmjs.com/package/axios,以了解有關如何使用axios庫發出HTTP請求的更多信息
再次恭喜😄 (Congrats Again 😄)
Now you know how to use components, how to communicate from a parent to a child component and also a little about rendering
現在,您知道了如何使用組件,如何從父組件與子組件進行通信以及有關渲染的一些知識。
The basic concepts have been covered in this post and hope this is helpful
這篇文章已經涵蓋了基本概念,希望對您有所幫助
關于作者 (About the author)
I love technology and follow the advancements in technology. I also like helping others with any knowledge I have in the technology space.
我熱愛技術,并追隨技術的進步。 我也喜歡以我在技術領域擁有的任何知識來幫助他人。
Feel free to connect with me on my LinkdIn account https://www.linkedin.com/in/aditya1811/
隨時通過我的LinkdIn帳戶與我聯系https://www.linkedin.com/in/aditya1811/
You can also follow me on twitter https://twitter.com/adityasridhar18
您也可以在Twitter上關注我https://twitter.com/adityasridhar18
My Website: https://adityasridhar.com/
我的網站: https : //adityasridhar.com/
我的其他相關帖子 (Other Relevant Posts by Me)
A Quick Guide to Help you Understand and Create Angular 6 Apps
幫助您了解和創建Angular 6應用程序的快速指南
A quick introduction to Vue.js
Vue.js快速介紹
翻譯自: https://www.freecodecamp.org/news/quick-guide-to-understanding-and-creating-reactjs-apps-8457ee8f7123/
reactjs快速如夢