一、背景
七镜在升级react-markdown v8.0.4
到 react-markdown v9.0.1
之后,启动前端代码时,出现如下错误:
[tsl] ERROR in D:\v3_workspace_personal\blog_client_v5\src\component\markdown\i-markdown\i-markdown.tsx(71,30)
TS2339: Property 'inline' does not exist on type 'ClassAttributes<HTMLElement> & HTMLAttributes<HTMLElement> & ExtraProps'.
ts-loader-default_e3b0c44298fc1c14
@ ./src/app/app-example/app-example.tsx 4:0-71 24:58-67
@ ./src/app/app.tsx 26:0-51 62:46-56
@ ./src/index.tsx 4:0-28 6:94-97
webpack 5.89.0 compiled with 1 error in 761 ms
出现报错的部分代码如下所示:
code:({node, inline, className, children, ...props})=> {
const match = /language-(\w+)/.exec(className || '')
return !inline && match ? (
<SyntaxHighlighter
showLineNumbers={true}
showInlineLineNumbers={true}
children={String(children).replace(/\n$/, '')}
// @ts-ignore
style={dark}
language={match[1]}
PreTag="div"
{...props}
/>
) : !inline && !match ? (
<SyntaxHighlighter
showLineNumbers={true}
children={String(children).replace(/\n$/, '')}
// @ts-ignore
style={dark}
language={'js'}
PreTag="div"
{...props}
/>
) : inline? (
<code className={"md-code-inline"} {...props}>
{children}
</code>
) : (
<code className={className} {...props}>
{children}
</code>
)
},
显而易见,新版本已经不支持传递 inline
了。
在 react-markdown
更新日志中也能找到这项更改:inline on code — create a plugin or use pre for the block
二、解决方案
在 pre 中增加如下代码:
pre: ({children,node}: any) => {
// 新增代码
if(node.children&&node.children[0]) {
if(node.children[0].tagName == "code") {
node.children[0].properties.inline = false
}
}
// 新增代码
return <Fragment>
<pre className="qijing-pre-element">
<CodeCopyBtn>{children}</CodeCopyBtn>
{children}
</pre>
</Fragment>
},
在 node 中判断如下:
code: ({children, className, node, ...rest}) => {
console.log("rest->",rest)
console.log("node->",node?.properties)
if(node?.properties.inline === false) {
console.log("")
}
// console.log(String(children).replace(/\n$/, ""))
const match = /language-(\w+)/.exec(className || '')
return node?.properties.inline === false ?match? (
<SyntaxHighlighter
style={dark}
language={match[1]}
PreTag="div"
showLineNumbers={true}
children={String(children).replace(/\n$/, "")}
/>
) : <SyntaxHighlighter
showLineNumbers={true}
children={String(children).replace(/\n$/, '')}
style={dark}
language={'js'}
PreTag="div"
/>:(<code className={"md-code-inline"} >
{children}
</code>)
},
网友评论