使用 JSX 将代码渲染到页面,同时保留换行符

我正在尝试使用一个包含大量代码的字段,其中包含换行符和制表符。我希望它呈现并保留制表符和换行符。


基本上我希望它在我输出时看起来像在堆栈溢出中格式化的代码。当我使用字符串文字时,它不会保留制表符和换行符。


下面是我的代码


import React, { useContext } from 'react'

import FunctionalContext from '../../context/functional/functionalContext';



const FunctionalComponent = () => {

  const functionalContext = useContext(FunctionalContext);


  return (

    <div>

      <h1>Classes</h1>

      <h2>Classes</h2>

      <code>{`

          import React from 'react'

        constructor() {

          super()

      `}

      </code>




    </div>

  )

}


export default FunctionalComponent


翻阅古今
浏览 311回答 1
1回答

慕虎7371278

code默认情况下,该元素未预先格式化。您可以将其中一种white-space样式应用于它,也可以将其放入pre元素中。不过,我认为您会很难以有用的方式呈现选项卡。在输出之前,您可能希望将它们扩展到作者使用的任何制表位。使用示例<pre><code>...</code></pre>:const Example = () => {&nbsp; const code =`import React from 'react';class Foo extends React.Component {&nbsp; &nbsp; constructor() {&nbsp; &nbsp; &nbsp; &nbsp; super();&nbsp; &nbsp; }}`;&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <h1>Classes</h1>&nbsp; &nbsp; &nbsp; <h2>Classes</h2>&nbsp; &nbsp; &nbsp; <pre><code>{code}</code></pre>&nbsp; &nbsp; </div>&nbsp; );}ReactDOM.render(<Example/>, document.getElementById("root"));<div id="root"></div><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script>使用white-space样式的示例:const Example = () => {&nbsp; const code =`import React from 'react';class Foo extends React.Component {&nbsp; &nbsp; constructor() {&nbsp; &nbsp; &nbsp; &nbsp; super();&nbsp; &nbsp; }}`;&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <h1>Classes</h1>&nbsp; &nbsp; &nbsp; <h2>Classes</h2>&nbsp; &nbsp; &nbsp; <code className="block">{code}</code>&nbsp; &nbsp; </div>&nbsp; );}ReactDOM.render(<Example/>, document.getElementById("root"));.block {&nbsp; &nbsp; display: block;&nbsp; &nbsp; white-space: pre;}<div id="root"></div><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script>我也包括在内,display: block因为默认情况下code是内联的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript