使用 React、Firebase 和 Ant Design 快速构建 Web 应用程序原型
本指南将向您展示如何使用Firebase、React和Ant Design作为构建模块来构建功能齐全、高保真的 Web 应用程序。为了更好地说明这一点,我们将通过构建一个待办事项列表应用程序的示例来进行讲解。
如今,Web 开发工具琳琅满目,令人眼花缭乱。该用哪个服务器?该选哪个前端框架?通常,建议使用自己最熟悉的技术。一般来说,这意味着选择一个久经考验的数据库,例如PostgreSQL或MySQL;选择一个 MVC 框架作为 Web 服务器(我个人最喜欢Adonis );然后使用该框架自带的渲染引擎,或者使用ReactJS或AngularJS等客户端 JavaScript 库。
上述方法确实有效——尤其是在有现成的模板可以快速上手的情况下——但如果你想快速构建产品,几乎不需要任何准备时间呢?有时,原型图无法向客户传达足够的信息;有时,你又想为新产品快速构建最小可行产品(MVP)。
本示例的源代码可在此处获取。如果您正在寻找一款适合本指南使用的优秀集成开发环境 (IDE),我强烈推荐 Visual Studio Code。
使用 Create React App 的 React 开发环境
React是一个用于构建用户界面的 JavaScript 库。该库采用“组件化”设计,这意味着您可以创建构建块,并使用这些可重用的组件来组合您的界面。而Create React App则是一个零配置的 React 环境。它只需一条 shell 命令即可开箱即用,并能保持您的环境始终处于最新状态。
首先,请按照此处的说明为您的系统安装Node.js。
然后开始你的新 Create React App 项目:
npx create-react-app quick-todo && cd quick-todo
现在,您可以使用以下命令运行开发 Web 服务器:
npm start
在浏览器中访问http://localhost:3000/,您应该会看到以下内容:
太棒了!你现在拥有一个功能齐全的 React 开发环境。
将 Firebase 与您的应用程序集成
现在你已经拥有了 React 开发环境,下一步就是将 Firebase 集成到你的应用中。Firebase 的核心产品是实时数据库服务。这意味着你的用户无需刷新页面即可查看应用状态的更新,而你也无需为此付出任何额外努力。
请访问https://firebase.google.com并创建一个帐户(如果您还没有帐户)。然后创建一个名为 . 的新 Firebase 项目quick-todo。
创建好 Firebase 项目后,配置一个“Cloud Firestore”数据库:
这里我们没有对数据库进行任何身份验证,因为我们正在构建一个原型。当你构建一个真正的应用程序时,你需要创建适当的安全规则,但我们现在暂且不考虑这一点。
好了,现在你的 Firebase 数据库已经配置好了,接下来我们把它集成到你的 React 应用中。在你的项目目录下,运行以下命令来安装必要的依赖项:
npm i --save firebase @firebase/app @firebase/firestore
src然后,在你的项目中,在名为 `<directory>` 的目录中添加一个新文件,firestore.js内容如下:
firestore.js
import firebase from "@firebase/app";
import "@firebase/firestore";
const config = {
apiKey: "<apiKey>",
authDomain: "<authDomain>",
databaseURL: "<databaseURL>",
projectId: "<projectId>",
storageBucket: "",
messagingSenderId: "<messageingSenderId>"
};
const app = firebase.initializeApp(config);
const firestore = firebase.firestore(app);
export default firestore;
请确保插入apiKey您项目中的参数和其他参数。您可以在项目设置中找到这些参数:
好了!现在,通过导入我们的实用程序,我们就可以在应用程序的任何位置访问实时 Firebase 数据库了firestore.js:
import firestore from "./firestore";
安装 Ant Design
Ant Design是一个功能全面的设计系统,包含一整套 React 组件。由于 React 是基于组件的,因此使用 Ant Design 的 React 组件作为构建模块,可以非常轻松地快速搭建原型。
要开始使用 Ant Design 的 React 组件系统,请安装antd:
npm i --save antd
整合所有信息
现在我们已经拥有构建原型所需的所有工具。让我们利用现有环境构建一个待办事项应用程序的高保真原型。
首先,让我们清空一切。修改它们App.js,App.css使它们看起来像这样:
App.js
import React, { Component } from "react";
import "./App.css";
class App extends Component {
render() {
return <div className="App" />;
}
}
export default App;
App.cs
@import "~antd/dist/antd.css";
.App {
text-align: center;
}
注意我们是如何导入 CSS 的antd。
现在,让我们为待办事项应用搭建一些基本结构。我们可以使用antd Layout组件来实现这一点:
App.js
import React, { Component } from "react";
import { Layout } from "antd";
import "./App.css";
const { Header, Footer, Content } = Layout;
class App extends Component {
render() {
return (
<Layout className="App">
<Header className="App-header">
<h1>Quick Todo</h1>
</Header>
<Content className="App-content">Content</Content>
<Footer className="App-footer">© My Company</Footer>
</Layout>
);
}
}
export default App;
App.css
@import "~antd/dist/antd.css";
.App {
text-align: center;
}
.App-header h1 {
color: whitesmoke;
}
.App-content {
padding-top: 100px;
padding-bottom: 100px;
}
完成这些更改后,我们就可以运行开发服务器了。您应该初始化类似这样的内容:
现在,我们可以使用firestore.js之前创建的模块,开始向实时 Firebase 数据库添加待办事项。您可以点击此处阅读更多关于如何使用 Firebase Cloud Firestore 的信息。
让我们逐步了解源代码的以下更改:
App.js
import React, { Component } from "react";
import { Layout, Input, Button } from "antd";
// We import our firestore module
import firestore from "./firestore";
import "./App.css";
const { Header, Footer, Content } = Layout;
class App extends Component {
constructor(props) {
super(props);
// Set the default state of our application
this.state = { addingTodo: false, pendingTodo: "" };
// We want event handlers to share this context
this.addTodo = this.addTodo.bind(this);
}
async addTodo(evt) {
// Set a flag to indicate loading
this.setState({ addingTodo: true });
// Add a new todo from the value of the input
await firestore.collection("todos").add({
content: this.state.pendingTodo,
completed: false
});
// Remove the loading flag and clear the input
this.setState({ addingTodo: false, pendingTodo: "" });
}
render() {
return (
<Layout className="App">
<Header className="App-header">
<h1>Quick Todo</h1>
</Header>
<Content className="App-content">
<Input
ref="add-todo-input"
className="App-add-todo-input"
size="large"
placeholder="What needs to be done?"
disabled={this.state.addingTodo}
onChange={evt => this.setState({ pendingTodo: evt.target.value })}
value={this.state.pendingTodo}
onPressEnter={this.addTodo}
/>
<Button
className="App-add-todo-button"
size="large"
type="primary"
onClick={this.addTodo}
loading={this.state.addingTodo}
>
Add Todo
</Button>
</Content>
<Footer className="App-footer">© My Company</Footer>
</Layout>
);
}
}
export default App;
App.css
@import "~antd/dist/antd.css";
.App {
text-align: center;
}
.App-header h1 {
color: whitesmoke;
}
.App-content {
padding-top: 100px;
padding-bottom: 100px;
}
.App-add-todo-input {
max-width: 300px;
margin-right: 5px;
}
.App-add-todo-button {
}
通过这些更改,您可以看到我们的应用程序现在可以添加新的待办事项。
虽然目前在用户界面中还不会显示添加待办事项的功能,但您可以浏览 Firebase 数据库来查看您添加的所有待办事项!
实现功能齐全的待办事项应用的最后一步是显示待办事项列表并允许用户完成它们。为此,我们可以使用Ant Design 的List组件来显示未完成的待办事项。以下是示例源代码:
App.js
import React, { Component } from "react";
import { Layout, Input, Button, List, Icon } from "antd";
// We import our firestore module
import firestore from "./firestore";
import "./App.css";
const { Header, Footer, Content } = Layout;
class App extends Component {
constructor(props) {
super(props);
// Set the default state of our application
this.state = { addingTodo: false, pendingTodo: "", todos: [] };
// We want event handlers to share this context
this.addTodo = this.addTodo.bind(this);
this.completeTodo = this.completeTodo.bind(this);
// We listen for live changes to our todos collection in Firebase
firestore.collection("todos").onSnapshot(snapshot => {
let todos = [];
snapshot.forEach(doc => {
const todo = doc.data();
todo.id = doc.id;
if (!todo.completed) todos.push(todo);
});
// Sort our todos based on time added
todos.sort(function(a, b) {
return (
new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
);
});
// Anytime the state of our database changes, we update state
this.setState({ todos });
});
}
async completeTodo(id) {
// Mark the todo as completed
await firestore
.collection("todos")
.doc(id)
.set({
completed: true
});
}
async addTodo() {
if (!this.state.pendingTodo) return;
// Set a flag to indicate loading
this.setState({ addingTodo: true });
// Add a new todo from the value of the input
await firestore.collection("todos").add({
content: this.state.pendingTodo,
completed: false,
createdAt: new Date().toISOString()
});
// Remove the loading flag and clear the input
this.setState({ addingTodo: false, pendingTodo: "" });
}
render() {
return (
<Layout className="App">
<Header className="App-header">
<h1>Quick Todo</h1>
</Header>
<Content className="App-content">
<Input
ref="add-todo-input"
className="App-add-todo-input"
size="large"
placeholder="What needs to be done?"
disabled={this.state.addingTodo}
onChange={evt => this.setState({ pendingTodo: evt.target.value })}
value={this.state.pendingTodo}
onPressEnter={this.addTodo}
required
/>
<Button
className="App-add-todo-button"
size="large"
type="primary"
onClick={this.addTodo}
loading={this.state.addingTodo}
>
Add Todo
</Button>
<List
className="App-todos"
size="large"
bordered
dataSource={this.state.todos}
renderItem={todo => (
<List.Item>
{todo.content}
<Icon
onClick={evt => this.completeTodo(todo.id)}
className="App-todo-complete"
type="check"
/>
</List.Item>
)}
/>
</Content>
<Footer className="App-footer">© My Company</Footer>
</Layout>
);
}
}
export default App;
App.css
@import "~antd/dist/antd.css";
.App {
text-align: center;
}
.App-header h1 {
color: whitesmoke;
}
.App-content {
padding-top: 100px;
padding-bottom: 100px;
}
.App-add-todo-input {
max-width: 300px;
margin-right: 5px;
}
.App-add-todo-button {
}
.App-todos {
background-color: white;
max-width: 400px;
margin: 0 auto;
margin-top: 20px;
margin-bottom: 20px;
}
.App-todo {
/* position: relative; */
}
.App-todo-complete {
font-size: 22px;
font-weight: bold;
cursor: pointer;
position: absolute;
right: 24px;
}
经过这些最终修改,我们可以将应用程序中添加的待办事项以列表形式显示:
瞧!我们利用 React、Firebase 和 Ant Design,快速创建了一个高保真度的 Web 应用程序。使用这些工具,您可以立即创建功能齐全且美观的应用程序。
当你需要向他人演示应用程序的功能,而又不想花费太多时间去构建它时,这会非常有价值。
本指南重点介绍如何使用工具快速构建原型,但我认为这种方法也适用于创建可用于生产环境的 Web 应用程序。Ant Design支持主题定制,而 Firebase 具有极强的可扩展性。
使用 Firebase 而非传统 Web 服务器的唯一问题在于成本。对于用户众多的应用,Firebase 的成本可能很快就会飙升;然而,使用传统的 Web 服务器和数据库方案也需要投入大量托管成本。此外,您还需要考虑构建、配置和管理 Web 服务器和数据库所需的时间和成本!
原文发表于nrempel.com
文章来源:https://dev.to/nbrempel/using-react-firebase-and-ant-design-to-quickly-prototype-web-applications-3hpa









