How to use whiteSpace: 'pre-wrap' on React

不羁岁月 提交于 2019-12-21 07:40:07

问题


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

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>
}

回答1:


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

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>



回答2:


You can use dangerouslySetInnerHTML but this is, well, dangerous. :) What else you can do, which is what we do in our app, is convert the string to React elements, for example to render line-breaks:

text.split("\n").map((text, i) => i ? [<br/>, text] : text)

You can make this into a function or a component like <MultilineText text={text}/>.

Example on CodePen.

In our case we also tried using whiteSpace and found that none of the options quite gave us what we wanted.



来源:https://stackoverflow.com/questions/36377373/how-to-use-whitespace-pre-wrap-on-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!