jsx表忽略换行符 [英] newlines character ignored by jsx table

查看:124
本文介绍了jsx表忽略换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用多行字符串创建一个表,但我的表格未正确格式化该字符串。这是jsx:

I am trying to create a table with a multiline string, but the string is not formatted correctly by my table. Here is the jsx:

<td>
  {arr.join('\n')}
</td>

这里是相应的html:

And here is the corresponding html:

<td data-reactid=".xyz">Line 1
Line 2
Line 3
Line 4</td>

但在浏览器中它看起来像:

But in the browser it looks like:

发生了什么事以及如何让我的新行出现?

What's going on and how do I get my newlines to appear?

推荐答案

你有几个选择:

1)使用块级元素,如 div p 并包装每个元素line。

1) Use a block level element such as div or a p and wrap each line.

var TextLines = React.createClass({      
    render: function() {
        var lines = this.props.lines;

        var formatted = lines.map(function(line) {
            return (<p>{line}</p>);
        });
        return (<div>{ formatted }</div>);
    }
});

var lines = ['line 1', 'line 2', 'line 3'];
React.render(<TextLines lines={ lines }/>, 
              document.getElementById('container'));

2)使用带有 br 的范围element:

2) Use a span with a br element:

var TextLines = React.createClass({      
    render: function() {
        var lines = this.props.lines;

        var br = lines.map(function(line) {
            return (<span>{line}<br/></span>);
        });
        return (<div>{ br }</div>);
    }
});

var lines = ['line 1', 'line 2', 'line 3'];
React.render(<TextLines lines={ lines } />,  
              document.getElementById('container'));

3)如果您确定没有XSS /黑客攻击数据的威胁,您可以使用 dangerouslySetInnerHTML 每行有一个'br':

3) If you're certain there is no threat of XSS/hacks with the data, you could use dangerouslySetInnerHTML with a 'br' for each line:

var TextLines = React.createClass({      
    render: function() {
        var lines = this.props.lines;
        var content = {
            __html: lines.join('<br />')
        };     
        return (<div dangerouslySetInnerHTML={ content } />);
    }
});

var lines = ['line 1', 'line 2', 'line 3'];
React.render(<TextLines lines={ lines } />, 
             document.getElementById('container'));

最后一个产生最少量的HTML,但代价是潜在风险的安全性网页/用户。如果其他人为你工作,我不会使用这个。

The last one produces the least amount of HTML, but at a cost of potentially risky the security of the web page/user. I wouldn't use this one if the others work for you.

这篇关于jsx表忽略换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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