使用 React App 文件夹结构构建随机报价机

2025-06-07

使用 React 构建随机报价机

应用程序文件夹结构

替代文本

点击此处查看演示

本教程介绍如何使用 React 构建一个简单的随机名言生成器,并使其能够在 Twitter 上分享。
本教程的目标是展示如何使用 React 状态和函数创建一个简单的 React 应用。

应用程序文件夹结构

使用Create-react-app创建一个样板,它将创建 Public 文件夹,其中包含 index.html 文件,以及包含组件文件夹的src文件夹。在 src 文件夹的根目录下,我们将包含index.jsApp.js文件。此应用仅包含前端部分。数据库位于src文件夹的根目录下,名为QuoteDB.js。我们将使用 bootstrap cdn 和 font awesome cdn。

创建 React 应用

创建 React 应用的最快方法是使用命令npx create-react-app random-quote 。这将创建样板文件,以准备我们的文件。

应用程序组件

src 文件夹中包含使用create-react-app创建的 App.js 文件,但现在我们将对其进行修改以适应我们的目的。首先,我们创建一个名为 components 的文件夹,并在其中创建一个名为QuoteAndAuthor.js的文件。我们使用 components 文件夹仅用于学习。我们完全可以在src文件夹的根目录下创建所有需要的文件。

App.js中,我们将创建一个状态对象,其中包含 quote 和 Author 作为属性,并创建一个generateRandomQuote函数,用于随机生成引言。记得从 react 文件夹导入react,从 components 文件夹导入 QuoteAndAuthor.js ,并从src文件夹的根目录导入数据库。这两个文件稍后会创建。

我们还有一个shuffleQuote函数,它可以在不同的点击时随机显示引言。我们在App.js中要做的最后一件事是返回QuoteAndAuthor.js组件,其中包含generateRandomQuote函数和状态对象。

import React, { Component } from 'react'
import QuoteAndAuthor from './components/QuoteAndAuthor';
import quotes from './QuoteDB';

export default class App extends Component {

  //state
  state = {
    quote: quotes[0].quote,
    author: quotes[0].author
  }

  //generate diffrent quote function
  generateRandomQuote = (arr) => {
    //get random numbers
    let num = Math.floor(Math.random() * quotes.length)

    let newQuote = quotes[num];

    //update state
    this.setState({
      quote: newQuote.quote,
      author: newQuote.author
    })

    this.shuffleQuotes(quotes)

  }

  //shuufle quotes function
  shuffleQuotes = (arr) => {
    return arr.sort(function () { return 0.5 - Math.random() });
  }

  render() {
    return (
      <div className="container">
        <h1 className="text-center">Random Quote</h1>
        <QuoteAndAuthor
          generateRandomQuote={this.generateRandomQuote}
          quote={this.state}
        />
      </div>
    )
  }
}

Index.js

index.js文件无需进行任何更改,我们将使用create-react-app样板创建的默认文件

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

serviceWorker.unregister();

索引.html

Index.html位于公共文件夹中,我们唯一要做的更改是添加 bootstrap 和 font awesome cdn 链接

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="theme-color" content="#000000" />
  <meta name="description" content="Web site created using create-react-app" />
  <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
  <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
  <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

  <!-- bootstrap-->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
    integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <title>Quote Generator - React App</title>
</head>

<body>
  <noscript>You need to enable JavaScript to run this app.</noscript>
  <div id="root"></div>

  <!--font awesome-->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/js/all.min.js"></script>

  <!-- bootstrap-->
  <script src="https://code.jquery.com/jquery-3.5.0.js" integrity="sha256-r/AaFHrszJtwpe+tHyNi/XCfMxYpbsRg2Uqn0x3s2zc="
    crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
    integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
    crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
    integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
    crossorigin="anonymous"></script>
</body>

</html>

QuoteAndAuthor.js

首先,在QuoteAndAuthor.js文件中,我们将导入 React 和数据库。这里我们将使用 React 函数,因为我们只需要显示App.js文件的输出。
QuoteAndAuthor.js文件中,我们需要将props传递给QuoteAndAuthor函数(默认情况下不会传递 props),然后解构 quote 和generateRandomQuote以便我们能够访问它们。
请注意,我们有两个按钮。一个用于生成名言,另一个用于在 Twitter 上分享名言。

import React from 'react'
import quotes from '../QuoteDB'

export default function QuoteAndAuthor(props) {

    const { quote, generateRandomQuote } = props;
    return (
        <div className="card" >

            <div className="card-body">
                <p className="card-text">{quote.quote}</p>
                <h5 className="card-title">- {quote.author}</h5>
                <button
                    onClick={() => { generateRandomQuote(quotes) }}
                    type="submit">
                    <i class="fas fa-mouse"></i> Generate Quote</button>
                <button
                    className="ml-3"
                    onClick={() => {
                        generateRandomQuote(quotes);
                        window.open('https://twitter.com/intent/tweet/?text=' + encodeURIComponent(quote.quote + '--' + quote.author))
                    }}
                    type="submit"><i class="fab fa-twitter"></i> Share Quote</button>
            </div>
        </div>
    )
}

数据库

对于这个项目,我们的数据库位于QuoteDB.js文件中,只是一个包含对象的数组。我们还需要导出此文件,以便其他组件和文件能够访问它。

const quotes = [
    {
        "quote": "Forget all the reasons why it won't work and believe the one reason why it will",
        "author": "Unknown"
    },
    {
        "quote": "Always do what you are afraid to do",
        "author": "Ralph Waldo Emerson"
    },

    {
        "quote": "Don’t be intimidated by what you don’t know. That can be your greatest strength and ensure that you do things differently from everyone else.",
        "author": "Sara Blakely"
    },
    {
        "quote": "If you keep on doing what you've always done, you will keep getting what you've always gotten.",
        "author": "Unknown"
    },
    {
        "quote": " For God so loved the world that he gave his one and only Son, that whoever believes in him shall not perish but have eternal life. John 3:16",
        "author": "Jesus Christ"
    },
    {
        "quote": "The surest way to find your dream job is to create it.",
        "author": "Unknown"

    }
]

export default quotes;

结论:使用 React 构建随机报价机

我们可以使用create-react-app创建一个简单的随机引言生成器。我们学到的知识包括使用npx create-react-app 创建 React 应用,它为我们创建了样板。在App.js中,我们使用了QuoteAndAuthor.js中的 React 状态组件和 React 函数组件来输出引言和作者,并创建了一个生成引言的函数。

我们还创建了一个QuoteDB.js文件,用于存放所有名言,并使用 Font Awesome 字体制作图标。恭喜,我们成功创建了一个名言生成器!运行npm start即可启动应用。祝您编程愉快!
Git 仓库在这里

封面照片由 Nathan Lemon 在 Unsplash 上拍摄

thinkc 图像
文章来源:https://dev.to/thinkc/build-a-random-quote-machine-with-react-41p4
PREV
Angular 正在获得新的模板语法
NEXT
Shell 脚本很重要