65 lines
1.6 KiB
TypeScript
65 lines
1.6 KiB
TypeScript
|
|
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;
|
||
|
|
};
|