使用< pre>格式化代码React和JSX中的标记 [英] Formatting code with <pre> tag in React and JSX

查看:383
本文介绍了使用< pre>格式化代码React和JSX中的标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在JSX中使用pre标签。当您在JSX中使用pre标签时,它根本不会格式化。为什么?为了使用pre标签,我需要做这样的事情:

I am trying to use the pre tag inside of JSX.When you use the pre tag in JSX, it doesn't format at all. Why? In order to use the pre tag I need to do something like this:

const someCodeIWantToFormat = "var foo = 1"
const preBlock = { __html: "<pre>" + pythonCode + "</pre>" };
return(
  <div dangerouslySetInnerHTML={ preBlock } />;
)

为什么?

推荐答案

使用模板文字



模板文字允许使用多行字符串它保留前/后空格和新行。

Use template literals

Template literals allow the use of multi-line strings which preserve leading/trailing white-space and new lines.

class SomeComponent extends React.Component {
   render() {
        return (
          <pre>{`
            Hello   ,   
            World   .
          `}</pre>
        )
    }
}

class SomeComponent extends React.Component {
   render() {
        return (
          <pre>{`
            Hello   ,   
            World   .
          `}</pre>
        )
    }
}

ReactDOM.render(
  <SomeComponent />, 
  document.getElementById('pre')
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react-dom.min.js"></script>

<div id="pre"></div>

<pre>
            Hello   ,
            World   .
</pre>

这篇关于使用&lt; pre&gt;格式化代码React和JSX中的标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆