import React from 'react'
import ReactDom from 'react-dom'
import ReactMarkdown from 'react-markdown'
import {Prism as SyntaxHighlighter} from 'react-syntax-highlighter'
import {atomDark} from 'react-syntax-highlighter/dist/esm/styles/prism'
// Did you know you can use tildes instead of backticks for code in markdown? ✨
const markdown = `Here is some JavaScript code:
~~~js
console.log('It works!')
~~~
`
ReactDom.render(
<ReactMarkdown
children={markdown}
components={{
code({node, inline, className, children, ...props}) {
return !inline && match ? (
<SyntaxHighlighter
children={String(children).replace(/\n$/, '')}
style={atomDark}
PreTag="div"
{...props}
/>
) : (
<code className={className} {...props}>
{children}
</code>
)
}
}}
/>,
document.body
)
当遇到code Block过短而不想高亮,或者含有特殊字符的code Block高亮
我们把上面的代码稍作修改
return !inline && (children[0].length > 40 || /\.\/|\//.test(children[0])) ? (
<SyntaxHighlighter
children={String(children).replace(/\n$/, '')}
style={atomDark}
PreTag="div"
{...props}
/>
)