现在后台是流式输出 markdown 字符串,并且每次我也不断处理全量的 markdown 字符串,再使用MarkdownContent这个组件去渲染成 html
但这样会导致一个问题,就是在流式输出的过程中,由于会不断地执行这个MarkdownView组件,导致无法使用鼠标选中渲染后的文本,等下次 render 时,选中状态就又丢失了
有什么方案能够增量更新吗,不操作以前的 dom
// 大概就这样的逻辑
function App() {
const [message, setMessage] = useState('')
async function foo() {
const reader = response.body?.getReader();
const decoder = new TextDecoder();
let result = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
result += decoder.decode(value);
setMessage(result);
}
}
return <MarkdownContent source={message}></MarkdownContent>;
}
export const MarkdownContent = memo(({ source }: MarkdownContentProps) => {
const html = useMemo(() => markdown.render(source ?? ""), [source])
return (
<article
className='prose dark:prose-invert'
style={{ maxWidth: "100%" }}
dangerouslySetInnerHTML={{ __html: html }}
/>
)
})
看了看chatgpt的dom结构,应该是对markdown内容进行了二次编译,才做到了增量更新的