如何配置MUI Alert使其识别消息中的换行符?
解决MUI Alert识别换行符且原样显示HTML字符串的问题
要同时实现识别消息中的换行符和原样展示HTML代码(不渲染),可以通过以下两种方式处理:
方法一:使用CSS white-space 属性(推荐)
React会自动转义HTML字符,直接渲染消息就能让<h1>Hi</h1>这类文本原样显示。要让换行符\n生效,只需给Alert或消息文本添加white-space: pre-line(合并连续空格,保留换行)或white-space: pre-wrap(保留空格和换行)样式即可。
修改后的代码示例:
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" sx={{ whiteSpace: 'pre-line' }}> <AlertTitle>Error</AlertTitle> {message} </Alert> </Stack> ); }
如果只想给消息文本单独设置样式,也可以把消息包裹在<span>中:
<Alert severity="error"> <AlertTitle>Error</AlertTitle> <span sx={{ whiteSpace: 'pre-line' }}>{message}</span> </Alert>
方法二:拆分字符串并插入换行标签
将消息按\n分割成数组,遍历数组并在每一行后插入<br>标签(最后一行除外):
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"; const splitMessage = message.split('\n'); return ( <Stack sx={{ width: "100%" }} spacing={2}> <Alert severity="error"> <AlertTitle>Error</AlertTitle> {splitMessage.map((line, index) => ( <React.Fragment key={index}> {line} {index !== splitMessage.length - 1 && <br />} </React.Fragment> ))} </Alert> </Stack> ); }
内容的提问来源于stack exchange,提问作者Big boy
相关产品推荐
相关产品推荐

