首页 > web前端 > js教程 > 使用 React 构建测验应用程序

使用 React 构建测验应用程序

王林
发布: 2024-09-10 11:31:30
原创
1085 人浏览过

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:管理布局并渲染测验组件。

代码说明

测验组件

测验组件负责呈现问题、计算分数以及处理测验完成。

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>{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>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中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板