React를 사용하여 퀴즈 애플리케이션 구축

王林
풀어 주다: 2024-09-10 11:31:30
원래의
904명이 탐색했습니다.

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;

로그인 후 복사

이 구성 요소는 질문과 옵션이 포함된 데이터 소품을 가져와 동적으로 렌더링합니다. handlerAnswer 함수는 선택한 옵션을 처리합니다.

앱 구성요소

App 구성요소는 레이아웃을 관리하고 퀴즈 구성요소를 렌더링합니다.

import Quiz from "./components/Quiz";
import "./App.css";
import React를 사용하여 퀴즈 애플리케이션 구축 from "./assets/images/quizReact를 사용하여 퀴즈 애플리케이션 구축.png";
const App = () => {
  return (
    <div classname="app">
      <img classname="React를 사용하여 퀴즈 애플리케이션 구축" src="%7BReact%EB%A5%BC" 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는 대화형의 매력적인 웹 애플리케이션 구축에 열정을 갖고 있는 웹 개발자입니다. GitHub에서 그의 작업을 팔로우할 수 있습니다.

위 내용은 React를 사용하여 퀴즈 애플리케이션 구축의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!