reactjs快速如梦_帮助您理解和创建ReactJS应用的快速指南

reactjs快速如梦

此帖子分为2部分 (This Post is divided into 2 parts)

  1. 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应用,并说明了项目结构。
  2. 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 .

创建项目时,您会注意到它创建了许多文件。 在这里,我将列出您应该注意的一些重要文件和文件夹。

  1. package.json: This File has the list of node dependencies which are needed.

    package.json:此文件包含所需的节点依赖项列表。

  2. 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。

  3. 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'));

  4. 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元素

  5. src/index.css: The CSS file corresponding to index.js.

    src / index.css :与index.js对应CSS文件。

  6. 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中的主要组件,它充当所有其他组件的容器。

  7. src/App.css : This is the CSS file corresponding to App Component

    src / App.css :这是与应用程序组件相对应CSS文件

  8. 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>)
    }
}
  1. 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

  2. The props attribute in the constructor will contain all the parameters which are passed as input to this component.

    构造函数中的props属性将包含所有作为输入传递到此组件的参数。

  3. 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

此代码段表明CustomerDetailsCustomers组件的子组件,并且还将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.valthis.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快速如梦

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值