使用 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中文網其他相關文章!

熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

Python和JavaScript開發者的薪資沒有絕對的高低,具體取決於技能和行業需求。 1.Python在數據科學和機器學習領域可能薪資更高。 2.JavaScript在前端和全棧開發中需求大,薪資也可觀。 3.影響因素包括經驗、地理位置、公司規模和特定技能。

如何在JavaScript中將具有相同ID的數組元素合併到一個對像中?在處理數據時,我們常常會遇到需要將具有相同ID�...

學習JavaScript不難,但有挑戰。 1)理解基礎概念如變量、數據類型、函數等。 2)掌握異步編程,通過事件循環實現。 3)使用DOM操作和Promise處理異步請求。 4)避免常見錯誤,使用調試技巧。 5)優化性能,遵循最佳實踐。

實現視差滾動和元素動畫效果的探討本文將探討如何實現類似資生堂官網(https://www.shiseido.co.jp/sb/wonderland/)中�...

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

深入探討console.log輸出差異的根源本文將分析一段代碼中console.log函數輸出結果的差異,並解釋其背後的原因。 �...
