跳到主要内容

react如何在react-syntax-highlighter中高亮显示某一行代码?

以下是来自stackoverflow的解决办法:

原文:Is it possible to highlight specific characters in a line using react-syntax-highlighter?

解决办法:

import React from "react";
import { PrismAsyncLight as SyntaxHighlighter } from "react-syntax-highlighter";
import { coy } from "react-syntax-highlighter/dist/cjs/styles/prism";

export type CodeViewerProps = {
language: string;
code: string;
linesToHighlight?: number[];
startingLineNumber?: number;
}

export function CodeViewer({
language, code, linesToHighlight = [], startingLineNumber = 1,
}: CodeViewerProps) {
return (
<SyntaxHighlighter
startingLineNumber={startingLineNumber}
language={language}
style={coy}
showLineNumbers
wrapLines
lineProps={(lineNumber) => {
const style = { display: "block", width: "fit-content" };
if (linesToHighlight.includes(lineNumber)) {
style.backgroundColor = "#ffe7a4";
}
return { style };
}}
>
{code}
</SyntaxHighlighter>
);
}

关键代码是

lineProps={(lineNumber) => {
const style = { display: "block", width: "fit-content" };
if (linesToHighlight.includes(lineNumber)) {
style.backgroundColor = "#ffe7a4";
}
return { style };
}}