搜尋
首頁web前端js教程使用 React 建立測驗應用程式

Building a Quiz Application with React

介紹

在本教學中,我們將引導您使用 React 建立一個有趣的互動式測驗網站。這個專案是初學者練習在 React 中處理使用者輸入、管理狀態和渲染動態內容的好方法。

項目概況

測驗網站允許使用者回答多項選擇題並獲得有關其選擇的即時回饋。測驗結束時,使用者會看到他們的分數以及正確答案。

特徵

  • 互動測驗:使用者可以回答問題並查看他們的分數。
  • 即時回饋:立即指示所選答案是否正確。
  • 分數計算:在整個測驗過程中追蹤分數。
  • 動態內容:問題和選項從預定義清單動態呈現。

使用的技術

  • React:用於建立使用者介面和管理元件狀態。
  • CSS:用於設計應用程式的樣式。
  • JavaScript:用於處理邏輯和測驗功能。

專案結構

專案的架構如下:

├── public
├── src
│   ├── components
│   │   ├── Quiz.jsx
│   │   ├── Question.jsx
│   ├── App.jsx
│   ├── App.css
│   ├── index.js
│   └── index.css
├── package.json
└── README.md

關鍵零件

  • Quiz.jsx:處理測驗邏輯和分數計算。
  • Question.jsx:顯示單一問題並處理使用者輸入。
  • App.jsx:管理佈局並渲染 Quiz 元件。

程式碼說明

測驗組件

測驗組件負責呈現問題、計算分數、處理測驗完成。

import  { useEffect, useState } from "react";
import Result from "./Result";
import Question from "./Question";
const data = [
  {
    question: "What is the capital of France?",
    options: ["Paris", "Berlin", "Madrid", "Rome"],
    answer: "Paris",
  },
  {
    question: "What is the capital of Germany?",
    options: ["Berlin", "Munich", "Frankfurt", "Hamburg"],
    answer: "Berlin",
  },
  {
    question: "What is the capital of Spain?",
    options: ["Madrid", "Barcelona", "Seville", "Valencia"],
    answer: "Madrid",
  },
  {
    question: "What is the capital of Italy?",
    options: ["Rome", "Milan", "Naples", "Turin"],
    answer: "Rome",
  },
  {
    question: "What is the capital of the United Kingdom?",
    options: ["London", "Manchester", "Liverpool", "Birmingham"],
    answer: "London",
  },
  {
    question: "What is the capital of Canada?",
    options: ["Ottawa", "Toronto", "Vancouver", "Montreal"],
    answer: "Ottawa",
  },
  {
    question: "What is the capital of Australia?",
    options: ["Canberra", "Sydney", "Melbourne", "Brisbane"],
    answer: "Canberra",
  },
  {
    question: "What is the capital of Japan?",
    options: ["Tokyo", "Osaka", "Kyoto", "Nagoya"],
    answer: "Tokyo",
  },
  {
    question: "What is the capital of China?",
    options: ["Beijing", "Shanghai", "Guangzhou", "Shenzhen"],
    answer: "Beijing",
  },
  {
    question: "What is the capital of Russia?",
    options: ["Moscow", "Saint Petersburg", "Novosibirsk", "Yekaterinburg"],
    answer: "Moscow",
  },
  {
    question: "What is the capital of India?",
    options: ["New Delhi", "Mumbai", "Bangalore", "Chennai"],
    answer: "New Delhi",
  },
  {
    question: "What is the capital of Brazil?",
    options: ["Brasilia", "Rio de Janeiro", "Sao Paulo", "Salvador"],
    answer: "Brasilia",
  },
  {
    question: "What is the capital of Mexico?",
    options: ["Mexico City", "Guadalajara", "Monterrey", "Tijuana"],
    answer: "Mexico City",
  },
  {
    question: "What is the capital of South Africa?",
    options: ["Pretoria", "Johannesburg", "Cape Town", "Durban"],
    answer: "Pretoria",
  },
  {
    question: "What is the capital of Egypt?",
    options: ["Cairo", "Alexandria", "Giza", "Luxor"],
    answer: "Cairo",
  },
  {
    question: "What is the capital of Turkey?",
    options: ["Ankara", "Istanbul", "Izmir", "Antalya"],
    answer: "Ankara",
  },
  {
    question: "What is the capital of Argentina?",
    options: ["Buenos Aires", "Cordoba", "Rosario", "Mendoza"],
    answer: "Buenos Aires",
  },
  {
    question: "What is the capital of Nigeria?",
    options: ["Abuja", "Lagos", "Kano", "Ibadan"],
    answer: "Abuja",
  },
  {
    question: "What is the capital of Saudi Arabia?",
    options: ["Riyadh", "Jeddah", "Mecca", "Medina"],
    answer: "Riyadh",
  },
  {
    question: "What is the capital of Indonesia?",
    options: ["Jakarta", "Surabaya", "Bandung", "Medan"],
    answer: "Jakarta",
  },
  {
    question: "What is the capital of Thailand?",
    options: ["Bangkok", "Chiang Mai", "Phuket", "Pattaya"],
    answer: "Bangkok",
  },
  {
    question: "What is the capital of Malaysia?",
    options: ["Kuala Lumpur", "George Town", "Johor Bahru", "Malacca"],
    answer: "Kuala Lumpur",
  },
  {
    question: "What is the capital of the Philippines?",
    options: ["Manila", "Cebu City", "Davao City", "Quezon City"],
    answer: "Manila",
  },
  {
    question: "What is the capital of Vietnam?",
    options: ["Hanoi", "Ho Chi Minh City", "Da Nang", "Hai Phong"],
    answer: "Hanoi",
  },
  {
    question: "What is the capital of South Korea?",
    options: ["Seoul", "Busan", "Incheon", "Daegu"],
    answer: "Seoul",
  },
];
const Quiz = () => {
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [score, setScore] = useState(0);
  const [showResult, setShowResult] = useState(false);
  const [timer, setTimer] = useState(30);
  const [showNextButton, setShowNextButton] = useState(true);

  useEffect(() => {
    if (timer === 0) {
      handleNext();
    }
    const timerId = setTimeout(() => setTimer(timer - 1), 1000);
    return () => clearTimeout(timerId);
  }, [timer]);

  const handleAnswer = (selectedOption) => {
    if (selectedOption === data[currentQuestion].answer) {
      setScore(score + 1);
    }
    setShowNextButton(true); // Show the next button after answering
  };

  const handleNext = () => {
    const nextQuestion = currentQuestion + 1;
    if (nextQuestion ;
  }

  return (
    <div classname="quiz">
<div classname="countandTime">
<div classname="questionNumber">
       Question :  {currentQuestion + 1} <b>/</b> {data.length}
      </div>
      <div classname="timer">Time left : {timer} seconds</div>
</div>
      <question question="{data[currentQuestion].question}" options="{data[currentQuestion].options}" onanswer="{handleAnswer}" onnext="{handleNext}" shownextbutton="{showNextButton}"></question>
    </div>
  );
};

export default Quiz;

測驗元件管理當前問題索引和分數。它還會追蹤測驗何時完成,並在回答所有問題後顯示最終分數。

問題成分

問題組件處理每個問題的顯示並允許使用者選擇答案。

const Question = ({ question, options, onAnswer, onNext, showNextButton }) => {
  return (
    <div classname="question">
      <h2 id="question">{question}</h2>
      {options.map((option, index) => (
        <button classname="option" key="{index}" onclick="{()"> onAnswer(option)}>
          {option}
        </button>
      ))}
      {showNextButton && <button classname="next" onclick="{onNext}">Next </button>}
    </div>
  );
};

export default Question;

該元件採用 data 屬性,其中包括問題及其選項,並動態呈現它。 handleAnswer 函數處理所選選項。

應用程式元件

App 元件管理佈局並渲染 Quiz 元件。

import Quiz from "./components/Quiz";
import "./App.css";
import 使用 React 建立測驗應用程式 from "./assets/images/quiz使用 React 建立測驗應用程式.png";
const App = () => {
  return (
    <div classname="app">
      <img classname="使用 React 建立測驗應用程式" src="%7B%E4%BD%BF%E7%94%A8" react alt="使用 React 建立測驗應用程式">
      <quiz></quiz>
      <p classname="footer">Made with ❤️ by Abhishek Gurjar</p>
    </div>
  );
};

export default App;

該元件透過頁首和頁尾建立頁面,測驗元件呈現在中心。

結果成分

結果元件負責在使用者提交答案後顯示他們的測驗分數。它透過將使用者的回答與正確答案進行比較來計算分數,並提供有關正確回答了多少個問題的回饋。

const Result = ({ score, totalQuestion }) => {
  return (
    <div classname="result">
      <h2 id="Quiz-Complete">Quiz Complete</h2>
      <p>Your score is {score} out of {totalQuestion}</p>
    </div>
  );
}

export default Result;

在此組件中,分數和問題總數作為 props 傳遞。根據分數,該組件向用戶顯示一條訊息,要么表揚他們正確回答所有問題,要么鼓勵他們繼續練習。這種動態回饋可以幫助使用者了解他們的表現。

CSS 樣式

CSS 確保測驗的版面乾淨簡單。它設計測驗組件的樣式並提供用戶友好的視覺效果。

* {
  box-sizing: border-box;
}
body {
  background-color: #cce2c2;
  color: black;
  margin: 0;
  padding: 0;
  font-family: sans-serif;
}
.app {
  width: 100%;

  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-direction: column;
}
.app img {
  margin: 50px;
}

/* Quiz */
.quiz {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 60%;
  margin: 0 auto;
}
.countandTime {
  display: flex;
  align-items: center;
  gap: 300px;
}
.questionNumber {
  font-size: 20px;
  background-color: #fec33d;
  padding: 10px;
  border-radius: 10px;
  font-weight: bold;
}
.timer {
  font-size: 18px;
  background-color: #44b845;
  color: white;
  padding: 10px;
  border-radius: 10px;
  font-weight: bold;
}

/* Question */

.question {
  margin-top: 20px;
}
.question h2 {
  background-color: #eaf0e7;
  width: 690px;
  padding: 30px;
  border-radius: 10px;
}
.question .option {
  display: flex;
  margin-block: 20px;
  flex-direction: column;
  align-items: flex-start;
  background-color: #eaf0e7;
  padding: 20px;
  border-radius: 10px;
  font-size: 18px;
  width: 690px;
}

.question .next {
  font-size: 25px;
  color: white;
  background-color: #35bd3a;
  border: none;
  padding: 10px;
  width: 100px;
  border-radius: 10px;

  margin-left: 590px;
}

/* Result */

.result {
  border-radius: 19px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  width: 500px;
  height: 300px;
  margin-top: 140px;
  background-color: #35bd3a;
  color: white;
}
.result h2{
  font-size: 40px;
}
.result p{
  font-size: 25px;
}

.footer {
  margin: 40px;
}

樣式確保佈局居中,並在測驗選項上提供懸停效果,使其更具互動性。

安裝與使用

要開始此項目,請複製儲存庫並安裝相依性:

git clone https://github.com/abhishekgurjar-in/quiz-website.git
cd quiz-website
npm install
npm start

這將啟動開發伺服器,並且應用程式將在 http://localhost:3000 上運行。

現場演示

在此處查看測驗網站的現場演示。

結論

這個測驗網站對於希望提高 React 技能的初學者來說是一個出色的專案。它提供了一種引人入勝的方式來練習管理狀態、呈現動態內容和處理使用者輸入。

製作人員

  • 靈感:專案的靈感來自於經典問答遊戲,將樂趣與學習融為一體。

作者

Abhishek Gurjar 是一位 Web 開發人員,熱衷於建立互動式且引人入勝的 Web 應用程式。您可以在 GitHub 上關注他的工作。

以上是使用 React 建立測驗應用程式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
在JavaScript中替換字符串字符在JavaScript中替換字符串字符Mar 11, 2025 am 12:07 AM

JavaScript字符串替換方法詳解及常見問題解答 本文將探討兩種在JavaScript中替換字符串字符的方法:在JavaScript代碼內部替換和在網頁HTML內部替換。 在JavaScript代碼內部替換字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 該方法僅替換第一個匹配項。要替換所有匹配項,需使用正則表達式並添加全局標誌g: str = str.replace(/fi

jQuery檢查日期是否有效jQuery檢查日期是否有效Mar 01, 2025 am 08:51 AM

簡單JavaScript函數用於檢查日期是否有效。 function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //測試 var

jQuery獲取元素填充/保證金jQuery獲取元素填充/保證金Mar 01, 2025 am 08:53 AM

本文探討如何使用 jQuery 獲取和設置 DOM 元素的內邊距和外邊距值,特別是元素外邊距和內邊距的具體位置。雖然可以使用 CSS 設置元素的內邊距和外邊距,但獲取準確的值可能會比較棘手。 // 設定 $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); 你可能會認為這段代碼很

10個jQuery手風琴選項卡10個jQuery手風琴選項卡Mar 01, 2025 am 01:34 AM

本文探討了十個特殊的jQuery選項卡和手風琴。 選項卡和手風琴之間的關鍵區別在於其內容面板的顯示和隱藏方式。讓我們深入研究這十個示例。 相關文章:10個jQuery選項卡插件

10值得檢查jQuery插件10值得檢查jQuery插件Mar 01, 2025 am 01:29 AM

發現十個傑出的jQuery插件,以提升您的網站的活力和視覺吸引力!這個精選的收藏品提供了不同的功能,從圖像動畫到交互式畫廊。讓我們探索這些強大的工具:相關文章:1

HTTP與節點和HTTP-Console調試HTTP與節點和HTTP-Console調試Mar 01, 2025 am 01:37 AM

HTTP-Console是一個節點模塊,可為您提供用於執行HTTP命令的命令行接口。不管您是否針對Web服務器,Web Serv

自定義Google搜索API設置教程自定義Google搜索API設置教程Mar 04, 2025 am 01:06 AM

本教程向您展示瞭如何將自定義的Google搜索API集成到您的博客或網站中,提供了比標準WordPress主題搜索功能更精緻的搜索體驗。 令人驚訝的是簡單!您將能夠將搜索限制為Y

jQuery添加捲軸到DivjQuery添加捲軸到DivMar 01, 2025 am 01:30 AM

當div內容超出容器元素區域時,以下jQuery代碼片段可用於添加滾動條。 (無演示,請直接複製到Firebug中) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前By尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器