如何解决Material-UI 样式和 html/markdown
我们的应用程序是使用 Material-UI 库(带主题)构建的。作为此应用程序的一部分,我们将 Markdown 解析为 html (marked library)。
如何将 material-ui 主题(Typography)应用到纯 html 中?
不知何故
<div dangerouslySetInnerHTML={ {__html: marked(markdown code)}}/>
应具有 material-ui Typography 定义的样式
解决方法
所有 Typography
变体的样式都在 theme.typography.<variant>
的主题中(您可以在此处浏览默认主题中的这些条目:https://material-ui.com/customization/default-theme/#default-theme)。您可以利用它来创建样式以定位您想要支持的标签,如下例所示:
import React from "react";
import { makeStyles } from "@material-ui/core";
import Typography from "@material-ui/core/Typography";
const useStyles = makeStyles((theme) => {
const tags = ["h1","h2","h3","h4","h5","h6"];
const nestedRules = {};
tags.forEach((tag) => {
nestedRules[`& ${tag}`] = { ...theme.typography[tag] };
});
return {
root: nestedRules
};
});
export default function App() {
const classes = useStyles();
return (
<Typography
className={classes.root}
variant="body1"
dangerouslySetInnerHTML={{
__html:
"<h1>H1</h1><h2>H2</h2><h3>H3</h3><h4>H4</h4><h5>H5</h5><h6>H6</h6><p>default body1</p>"
}}
></Typography>
);
}
相关答案:material-ui makeStyles: how to style by tag name?
,使用 markdown-to-jsx
npm 包。 here 是来自 Material ui 模板的示例。
你基本上必须创建一个 ReactMarkdown 喜欢的配置对象,特定于材料 ui
import React from 'react';
import ReactMarkdown from 'markdown-to-jsx';
import { withStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import Link from '@material-ui/core/Link';
const styles = (theme) => ({
listItem: {
marginTop: theme.spacing(1),},});
const options = {
overrides: {
h1: {
component: Typography,props: {
gutterBottom: true,variant: 'h5',h2: { component: Typography,props: { gutterBottom: true,variant: 'h6' } },h3: { component: Typography,variant: 'subtitle1' } },h4: {
component: Typography,variant: 'caption',paragraph: true },p: { component: Typography,props: { paragraph: true } },a: { component: Link },li: {
component: withStyles(styles)(({ classes,...props }) => (
<li className={classes.listItem}>
<Typography component="span" {...props} />
</li>
)),};
export default function Markdown(props) {
return <ReactMarkdown options={options} {...props} />;
}
我直接从他们的例子中得到了这一点。
,使用常规的 Typography
组件并以与在问题中传递的方式类似的方式传递该 HTML。
<Typography
variant="h2"
color="primary"
dangerouslySetInnerHTML={{ __html: "<p>Hi from inner HTML</p>" }}>
</Typography>
这里有一个问题,当 dangerouslySetInnerHTML
被传递时,不要将任何东西作为孩子传递。
这是一个工作演示:
注意:还要确保函数 marked(markdown code)
以字符串形式返回 HTML。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。