安装react-markdown react-syntax-highlighter
npm i react-markdown react-syntax-highlighter
引入react-markdown react-syntax-highlighter
import ReactMarkdown from 'react-markdown'
import {Prism as SyntaxHighlighter} from 'react-syntax-highlighter'
import {duotoneLight} from 'react-syntax-highlighter/dist/esm/styles/prism'
components
~~~js
const Test = React.lazy(() => import('你的组件'));
<Suspense fallback="loading...">
<Test />
</Suspense>
~~~
const article = () => {
const [content, setContent] = useState("");
const { id } = useParams();
const url = `/markdown/article-${id}.md`;
useEffect(() => {
fetch(url)
.then((res) => res.text())
.then((text) => setContent(text));
}, []);
return (
<div><ReactMarkdown
children={content}
components={{
code({node, inline, className, children, ...props}) {
const match = /language-(\w+)/.exec(className || '')
return !inline && match ? (
<SyntaxHighlighter
children={String(children).replace(/\n$/, '')}
style={duotoneLight}
language={match[1]}
PreTag="div"
{...props}
/>
) : (
<code className={className} {...props}>
{children}
</code>
)
}
}}/></div>
);
}
export default article;
最后编辑于 :2023.10.26 16:00:31
©著作权归作者所有,转载或内容合作请联系作者 平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。