如何在React JS的多行字符串中使用Markdown行内代码引号符号?
解决模板字符串中反引号复用问题及代码优化
核心问题解决:转义反引号
在ES6模板字符串中,若要在字符串内部使用反引号(),只需在反引号前添加反斜杠转义:``,就能在默认示例文本中正确展示行内代码的Markdown语法。
修改后的完整代码
function App() { // 对行内代码的反引号进行转义处理 const [markdownText, setMarkdownText] = React.useState(`# Type your markdown text here ## then type enter or any other key to see it translated into an HTML format here is a [link](https://commonmark.org/help/) with basics markdown styling methods \`Inline code\` with backticks `) const [markdowned, setMarkdowned] = React.useState("") // 修复useEffect逻辑,添加依赖数组避免无限循环 React.useEffect(() => { textToMarkdown() }, [markdownText]) const handleChange = (e) => { setMarkdownText(e.target.value) } const textToMarkdown = () => { setMarkdowned(marked.parse(markdownText)); } return ( <div className="row"> <h1 className="text-center m-4">Convert your markdown</h1> <h3 className="text-center m-4">Tap enter after your last key to see the result</h3> <div className="col-6 border bg-danger"> <h5 className="text-center"> Markdown: </h5> <textarea onChange={handleChange} defaultValue={markdownText} id="editor" className="border-danger container-fluid box"/> </div> <div className="col-6 border bg-warning"> <h5 className="text-center"> HTML: </h5> <div id="preview" className="border border-info rounded p-1 container-fluid box bg-light" dangerouslySetInnerHTML={{ __html: markdowned }}/> </div> </div> ) } const container = document.getElementById('root'); const root = ReactDOM.createRoot(container); root.render(<App />);
额外代码优化说明
- 修复useEffect逻辑:原代码中useEffect的写法存在错误,不仅没有有效执行副作用,还缺少依赖数组会导致组件无限重渲染。修改后添加依赖数组
[markdownText],仅当文本内容变化时执行转换,同时移除无效的数组写法。 - 简化handleChange:无需在输入变化时直接调用转换函数,依赖useEffect监听文本变化自动执行转换,避免重复调用。
内容的提问来源于stack exchange,提问作者Reggroy
相关产品推荐
相关产品推荐

