[英]Issue with marked library with React when using Babel
I have met issues using marked
library in my React app.我在我的 React 应用程序中使用
marked
库时遇到了问题。
The app has been created by adding Babel to HTML/CSS/JS environment and using other libraries like Bootstrap.该应用程序是通过将 Babel 添加到 HTML/CSS/JS 环境并使用其他库(如 Bootstrap)创建的。
It seems that marked parse the text that I put in my box but then gives a gibberish HTML result without applying the design.似乎标记为解析了我放入框中的文本,但随后在未应用设计的情况下给出了乱码 HTML 结果。
I just do not get why the result looks like that and the delay.我只是不明白为什么结果看起来像那样和延迟。
function App() {
const [markdownText, setMarkdownText] = React.useState("When my markdown previewer first loads, the default text in the #editor field should contain valid markdown that represents at least one of each of the following elements: a heading element (H1 size), a sub heading element (H2 size), a link, inline code, a code block, a list item, a blockquote, an image, and bolded text.")
const [markdowned, setMarkdowned] = React.useState("")
const handleChange = (e) => {
setMarkdownText(e.target.value)
textToMarkdown()
}
const textToMarkdown = () => {
console.log('here')
setMarkdowned(marked.parse(markdownText));
return dangerouslySetInnerHTML={ __html: markdowned };
}
return (
<div className="row">
<h1 className="text-center m-4">Convert your markdown</h1>
<div className="col-6 border bg-danger">
<h5 className="text-center">
Markdown:
</h5>
<textarea
onChange={handleChange}
value={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">
{markdowned}
</div>
</div>
</div>
)
}
const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(<App />);
All other sources I have found to try to fix this issue are using the regular React env with an extension of components.我发现尝试解决此问题的所有其他资源都使用带有组件扩展的常规 React env。
Am I missing something?我错过了什么吗? What do I do wrong?
我做错了什么?
Thanks in advance for your help.在此先感谢您的帮助。
Call textToMarkdown inside a useEffect (having markdownText as a dependency) instead of handleChange.在 useEffect 中调用 textToMarkdown(将 markdownText 作为依赖项)而不是 handleChange。 Below are the changes to be made
以下是要进行的更改
const handleChange = (e) => {
setMarkdownText(e.target.value)
// textToMarkdown(text);
}
React.useEffect(() => {
textToMarkdown();
}, [markdownText]) // execute textToMarkdown(); whenever there is a change to markdownText
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.