从零搭建基于 AI 问答平台(6) Quiz Page/Form

效果

实现步骤如下:

添加 Quiz 页面

安装:

1
2
3
4
bunx --bun shadcn@latest add form
bunx --bun shadcn@latest add input
bunx --bun shadcn@latest add separator
bun add zod

添加 src/app/quiz/page.tsx:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import React from 'react';
import { auth } from '@clerk/nextjs/server';
import { redirect } from 'next/navigation';
import { QuizCreation } from '@/components/forms/QuizCreation';

export const metadata = {
title: 'Quiz | Smartquiz',
};

const Quiz = async () => {
const { userId } = await auth();

if (!userId) {
return redirect('/');
}

return (
<QuizCreation topic='Test' />
)
}

export default Quiz;

添加 Form

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";

<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
...
<Button disabled={isLoading} type="submit">
Submit
</Button>
</form>
</Form>

注:from 在下面章节定义。

添加 Zod 校验

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
export const quizCreationSchema = z.object({
topic: z
.string()
.min(4, {
message: "Topic must be at least 4 characters long",
})
.max(50, {
message: "Topic must be at most 50 characters long",
}),
type: z.enum(["mcq", "open_ended"]),
amount: z.number().min(1).max(10),
});

const form = useForm<Input>({
resolver: zodResolver(quizCreationSchema),
defaultValues: {
topic: topicParam,
type: "mcq",
amount: 3,
},
});

添加 Form Field

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
<FormField
control={form.control}
name="amount"
render={({ field }) => (
<FormItem>
<FormLabel>Number of Questions</FormLabel>
<FormControl>
<Input
placeholder="How many questions?"
type="number"
{...field}
onChange={(e) => {
form.setValue("amount", parseInt(e.target.value));
}}
min={1}
max={10}
/>
</FormControl>
<FormDescription>
You can choose how many questions you would like to be
quizzed on here.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>

添加二选一按钮

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
<div className="flex justify-between">
<Button
variant={
form.getValues("type") === "mcq" ? "default" : "secondary"
}
className="w-1/2 rounded-none rounded-l-lg"
onClick={() => {
form.setValue("type", "mcq");
}}
type="button"
>
<CopyCheck className="w-4 h-4 mr-2" /> Multiple Choice
</Button>
<Separator orientation="vertical" />
<Button
variant={
form.getValues("type") === "open_ended"
? "default"
: "secondary"
}
className="w-1/2 rounded-none rounded-r-lg"
onClick={() => form.setValue("type", "open_ended")}
type="button"
>
<BookOpen className="w-4 h-4 mr-2" /> Open Ended
</Button>
</div>

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

请我喝杯咖啡吧~

支付宝
微信