从零搭建基于 AI 问答平台(12) 完善 mcq 模块

效果

实现步骤如下:

添加 MCQCounter 模块

修改 src/components/play/MCQCounter.tsx:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import React from "react";
import { Card } from "@/components/ui/card";
import { CheckCircle2, XCircle } from "lucide-react";
import { Separator } from "@radix-ui/react-separator";

type Props = {
correct_answers: number;
wrong_answers: number;
};

const MCQCounter = ({ correct_answers, wrong_answers }: Props) => {
return (
<Card className="flex flex-row items-center justify-center p-2">
<CheckCircle2 color="green" size={30} />
<span className="mx-3 text-2xl text-[green]">{correct_answers}</span>

<Separator orientation="vertical" />

<span className="mx-3 text-2xl text-[red]">{wrong_answers}</span>
<XCircle color="red" size={30} />
</Card>
);
};

export default MCQCounter;

支持键盘输入

修改 src/components/play/MCQ.tsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
const key = event.key;

if (key === "1") {
setSelectedChoice(0);
} else if (key === "2") {
setSelectedChoice(1);
} else if (key === "3") {
setSelectedChoice(2);
} else if (key === "4") {
setSelectedChoice(3);
} else if (key === 'ArrowUp') {
setSelectedChoice(prevChoice => (prevChoice - 1 + 4) % 4);
} else if (key === 'ArrowDown') {
setSelectedChoice(prevChoice => (prevChoice + 1) % 4);
} else if (key === "Enter") {
handleNext();
}
};

document.addEventListener("keydown", handleKeyDown);

return () => {
document.removeEventListener("keydown", handleKeyDown);
};
}, [handleNext]);

注意,更新hook内的变量要用箭头函数。

添加计时器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 const [now, setNow] = React.useState(new Date());

React.useEffect(() => {
const interval = setInterval(() => {
if (!hasEnded) {
setNow(new Date());
}
}, 1000);
return () => clearInterval(interval);
}, [hasEnded]);

<div className="flex self-start mt-3 text-slate-400">
<Timer className="mr-2" />
{formatTimeDelta(differenceInSeconds(now, game.timeStarted))}
</div>

如果感兴趣本项目,请访问项目目录: 从零搭建基于 AI 问答平台 - 目录


作者:Bearalise
出处:从零搭建基于 AI 问答平台(12) 完善 mcq 模块
版权:本文版权归作者所有
转载:欢迎转载,但未经作者同意,必须保留此段声明,必须在文章中给出原文链接。

请我喝杯咖啡吧~

支付宝
微信