如何使 MUI 对话框标题成为 H1 元素,以便可以访问模式

Lai*_*ghi 3 html javascript accessibility reactjs material-ui

我正在努力使我的应用程序更易于访问,并且正在努力使用 MUI 对话框组件。我正在使用 DialogTitle 组件,它创建一个 H2 元素,但遇到“页面不包含一级标题”的问题。我应该以其他方式创建模式,还是 MUI 对话框无法访问?

import { Dialog, DialogTitle } from '@mui/material';

const MyModal = () => {

    return (
        <Dialog open={true}>
            <DialogTitle>
                My Title
            </DialogTitle>
        </Dialog>
    );
};

export default MyModal;
Run Code Online (Sandbox Code Playgroud)

Ste*_*mez 9

针对 MUI v5 进行了更新:

组件DialogAPI 包括一个辅助DialogTitle组件,默认情况下,该组件在h2元素内呈现其内容。要更改此功能,您可以将该component属性传递给 ,以便使用您希望的任何内容DialogTitle进行渲染。例如:DialogTitleelementType

<DialogTitle component="h1">
  My Dialog Title
</DialogTitle>
Run Code Online (Sandbox Code Playgroud)

目前这是 的一个未记录的功能,但从源代码DialogTitle中可以看出,传递给的属性会传播到底层组件上——通过传递,您实际上是用自己的值覆盖硬编码的prop。DialogTitleTypographycomponentcomponent="h2"

工作示例: https: //codesandbox.io/s/simpledialog-material-demo-forked-kpq9k? file=/demo.js

MUI v4 的原始答案:

组件DialogAPI 包括一个辅助DialogTitle组件,默认情况下,该组件在h2元素内呈现其内容。要禁用此功能,您可以使用DialogTitle带有disableTypographyprop 的组件(以禁用h2包装行为),然后将您自己的Typography组件设置为h1. 例如:

<DialogTitle disableTypography>
  <Typography variant="h1">My Dialog Title</Typography>
</DialogTitle>
Run Code Online (Sandbox Code Playgroud)

工作示例:https ://codesandbox.io/s/material-demo-forked-7pso2?file=/demo.js

额外加分:您可能会遇到这样的问题:h1对于您的设计来说,样式“太大”。如果是这样,并且您更喜欢这种h2外观,则可以将Typography命名的 propcomponent与 prop 结合使用variant,以在视觉上将其样式恢复为h2,同时保留底层h1元素。例如:

<DialogTitle disableTypography>
  <Typography variant="h2" component="h1">My Dialog Title</Typography>
</DialogTitle>
Run Code Online (Sandbox Code Playgroud)


hak*_*ogh 5

对于 TypeScript,没有提供任何类型,因此您需要进行修改:

<DialogTitle {...{ component: 'div' } as any}>
  <Typography variant="h1">My Dialog Title</Typography>
</DialogTitle>
Run Code Online (Sandbox Code Playgroud)

这是一个临时黑客,直到他们为所有道具添加打字。