繁体   English   中英

使用 Babel 时 React 标记库出现问题

[英]Issue with marked library with React when using Babel

我在我的 React 应用程序中使用marked库时遇到了问题。

该应用程序是通过将 Babel 添加到 HTML/CSS/JS 环境并使用其他库(如 Bootstrap)创建的。

似乎标记为解析了我放入框中的文本,但随后在未应用设计的情况下给出了乱码 HTML 结果。

我只是不明白为什么结果看起来像那样和延迟。

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 />);

我发现尝试解决此问题的所有其他资源都使用带有组件扩展的常规 React env。

我错过了什么吗? 我做错了什么?

在此先感谢您的帮助。

链接到codepen上的项目

链接到Github上的回购协议

在 useEffect 中调用 textToMarkdown(将 markdownText 作为依赖项)而不是 handleChange。 以下是要进行的更改

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM