如何配置 MUI 警报以支持消息中的换行?

Big*_*boy 2 reactjs material-ui

这是我的代码:

import * as React from "react";
import Alert from "@mui/material/Alert";
import AlertTitle from "@mui/material/AlertTitle";
import Stack from "@mui/material/Stack";

export default function DescriptionAlerts() {
  const message =
    "This is a message \n This message has Enter in it \n MUI Alert does not honor the Enter \n I can not use dangerouslySetInnerHTML \n Because this message contains <h1>Hi</h1> in it \n And I want to show that HTML string to my user \n I don't want to render that HTML";
  return (
    <Stack sx={{ width: "100%" }} spacing={2}>
      <Alert severity="error">
        <AlertTitle>Error</AlertTitle>
        {message}
      </Alert>
    </Stack>
  );
}
Run Code Online (Sandbox Code Playgroud)

这是一个实时CodeSandbox,展示了它的实际效果。

我收到一条来自 API 的消息。此消息包含需要以 HTML 代码形式向用户显示的 HTML,而不需要进行渲染。因此 AMAIK 我无法使用dangerouslySetInnerHTML.

然而,它有一些新的行字符。我如何告诉 MUI Alert 遵守这些新线路?

小智 8

您必须添加white-space: pre-line;样式Alert

<Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>
    {message}
</Alert>
Run Code Online (Sandbox Code Playgroud)