NextJs/ReactJs中ShadCN/UI的DialogContent需DialogTitle错误排查求助
问题场景
在Next.js/React项目中使用ShadCN/UI的Dialog组件,已确认所有DialogContent内部包含DialogTitle,且组件均正确从ShadCN导入(无Radix误导入),但控制台仍持续报错:
DialogContentrequires aDialogTitlefor the component to be accessible for screen reader users.
If you want to hide theDialogTitle, you can wrap it with our VisuallyHidden component.
示例代码:
<Dialog open={isModalOpen} onOpenChange={handleClose}> <DialogContent className='bg-white text-black p-0 overflow-hidden' aria-describedby='create-channel' > <DialogHeader className='pt-8 px-6'> <DialogTitle id='create-channel' className='text-2xl text-center font-bold' > Create Channel </DialogTitle> </DialogHeader> <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className='space-y-8'> <div className='space-y-8 px-6'> <FormField control={form.control} name='name' render={({ field }) => ( <FormItem> <FormLabel className='uppercase text-xs font-bold text-zinc-500 dark:text-secondary/70'> Channel Name </FormLabel> <FormControl> <Input disabled={isLoading} className='bg-zinc-300/50 border-0 focus-visible:ring-0 text-black focus-visible:ring-offset-0' placeholder='Enter Channel Name...' {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name='type' render={({ field }) => ( <FormItem> <FormLabel>Channel Type</FormLabel> <Select disabled={isLoading} onValueChange={field.onChange} defaultValue={field.value} > <FormControl> <SelectTrigger className='bg-zinc-300/50 border-0 focus:ring-0 text-black ring-offset-0 focus:ring-offset-0 capitalize outline-none'> <SelectValue placeholder='Select a Channel Type' /> </SelectTrigger> </FormControl> <SelectContent> {Object.values(ChannelType).map((type) => ( <SelectItem key={type} value={type} className='captialize' > {capitalizeFirstLetterOfEachWord( type.toLowerCase() )} </SelectItem> ))} </SelectContent> </Select> <FormMessage /> </FormItem> )} /> </div> <DialogFooter className='bg-gray-100 px-6 py-4'> <Button variant={'primary'}>Create</Button> </DialogFooter> </form> </Form> </DialogContent> </Dialog>
排查步骤
修正无障碍属性关联
代码中DialogContent使用了aria-describedby='create-channel',但该属性用于关联描述性内容,对话框标题应使用aria-labelledby关联DialogTitle的id。将DialogContent的属性修改为:<DialogContent className='bg-white text-black p-0 overflow-hidden' aria-labelledby='create-channel' >若需要额外描述内容,再单独添加
aria-describedby关联对应元素的id。校验组件版本一致性
ShadCN Dialog基于Radix UI封装,版本不兼容可能触发校验异常。重新安装ShadCN Dialog组件确保版本匹配:npx shadcn-ui@latest add dialog检查Dialog实例状态
排查项目中是否存在多个Dialog同时打开,或某个Dialog的open状态未正确更新导致残留实例。确保所有Dialog的状态逻辑正确,同一时间仅一个Dialog处于打开状态。确认DialogTitle无条件渲染
检查DialogTitle是否被条件渲染(如{showTitle && <DialogTitle />}),即使当前显示,组件内部校验仍可能触发错误。确保DialogTitle始终存在于DialogContent内部。验证DOM结构完整性
在浏览器开发者工具中查看渲染后的DOM,确认DialogTitle确实是DialogContent的后代元素,未被自定义样式(如display: none)或组件包裹移出DOM树。
内容的提问来源于stack exchange,提问作者Zack Murray

