如何使用whiteSpace:React上的“预包装" [英] How to use whiteSpace: 'pre-wrap' on React

查看:228
本文介绍了如何使用whiteSpace:React上的“预包装"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在React上使用样式whiteSpace:'pre-wrap'

How can I use the style whiteSpace: 'pre-wrap' on React

我有一个div,需要使用带有空格的格式来呈现文本

I have a div that need to render the text using the format with spaces

render() {
   <div style={{whiteSpace: 'pre-wrap'}}
      keep formatting

      keep spaces
   </div>
}

推荐答案

JSX折叠空格,在这种情况下,您可以使用

JSX collapses whitespaces, in this case you can use dangerouslySetInnerHTML like so

var Component = React.createClass({
  content() {
    const text = `
      keep formatting

      keep spaces
   `;

    return { __html: text };
  },

  render: function() {
    return <div 
      style={{ whiteSpace: 'pre-wrap' }} 
      dangerouslySetInnerHTML={ this.content() } 
    />
  }
});

注意:对于新版本的React/JSX,无需使用dangerouslySetInnerHTML

Note: For new versions of React/JSX, there is no need to use dangerouslySetInnerHTML

const App = () => (
  <div style={{ whiteSpace: 'pre-wrap' }}>
    {`
      keep formatting

      keep spaces


      keep spaces
   `}
  </div>
);

ReactDOM.render(<App />, document.getElementById('root'));

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

这篇关于如何使用whiteSpace:React上的“预包装"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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