第一版提交,答题功能OK,题库管理待完善
This commit is contained in:
65
src/contexts/QuizContext.tsx
Normal file
65
src/contexts/QuizContext.tsx
Normal file
@@ -0,0 +1,65 @@
|
||||
import { createContext, useContext, useState, ReactNode } from 'react';
|
||||
|
||||
interface Question {
|
||||
id: string;
|
||||
content: string;
|
||||
type: 'single' | 'multiple' | 'judgment' | 'text';
|
||||
options?: string[];
|
||||
answer: string | string[];
|
||||
score: number;
|
||||
createdAt: string;
|
||||
category?: string;
|
||||
}
|
||||
|
||||
interface QuizContextType {
|
||||
questions: Question[];
|
||||
setQuestions: (questions: Question[]) => void;
|
||||
currentQuestionIndex: number;
|
||||
setCurrentQuestionIndex: (index: number) => void;
|
||||
answers: Record<string, string | string[]>;
|
||||
setAnswer: (questionId: string, answer: string | string[]) => void;
|
||||
clearQuiz: () => void;
|
||||
}
|
||||
|
||||
const QuizContext = createContext<QuizContextType | undefined>(undefined);
|
||||
|
||||
export const QuizProvider = ({ children }: { children: ReactNode }) => {
|
||||
const [questions, setQuestions] = useState<Question[]>([]);
|
||||
const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
|
||||
const [answers, setAnswers] = useState<Record<string, string | string[]>>({});
|
||||
|
||||
const setAnswer = (questionId: string, answer: string | string[]) => {
|
||||
setAnswers(prev => ({
|
||||
...prev,
|
||||
[questionId]: answer
|
||||
}));
|
||||
};
|
||||
|
||||
const clearQuiz = () => {
|
||||
setQuestions([]);
|
||||
setCurrentQuestionIndex(0);
|
||||
setAnswers({});
|
||||
};
|
||||
|
||||
return (
|
||||
<QuizContext.Provider value={{
|
||||
questions,
|
||||
setQuestions,
|
||||
currentQuestionIndex,
|
||||
setCurrentQuestionIndex,
|
||||
answers,
|
||||
setAnswer,
|
||||
clearQuiz
|
||||
}}>
|
||||
{children}
|
||||
</QuizContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useQuiz = () => {
|
||||
const context = useContext(QuizContext);
|
||||
if (!context) {
|
||||
throw new Error('useQuiz必须在QuizProvider内使用');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
Reference in New Issue
Block a user