javascript 使 <br /> 来自字符串在反应中起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33579051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make <br /> from string works in react
提问by namelos
Here are some ajax calls returns <br />
in their data, while I found it was hard to handle.
这里有一些 ajax 调用<br />
在他们的数据中返回,而我发现它很难处理。
Here is what I got for now, but not working at all. The string was split correctly, while react gave me several <span></span>
tags without proper <br />
line breaks.
这是我现在得到的,但根本不起作用。字符串被正确拆分,而 react 给了我几个<span></span>
没有正确<br />
换行符的标签。
const breakLine = text => {
const regex = /<br\s*[\/]?>/gi
return text.split(regex).map(
line => line.match(regex) ? React.createElement('br') : line
)
}
const Text = ({ content }) => <p>
{ breakLine(content) }
<p>
// Usage
<Text content="Here are some <br /> Lines <br> to break!" />
采纳答案by Henrik Andersson
When you split using the regex your array will not contain the <br />
tags as split removes the delimiter.
当您使用正则表达式拆分时,您的数组将不包含<br />
标签,因为拆分会删除分隔符。
let splitText = text.split(regext);
// ["Here are some ", " Lines ", " to break!"]
Which makes your ternary always hit the false clause and only return the actual line.
这使您的三元总是遇到 false 子句并且只返回实际行。
One way of doing it can be found in this answer
可以在此答案中找到一种方法
Working example regex courtesy of @JonMayer
@JonMayer 提供的工作示例正则表达式
function breakLine(text) {
var br = React.createElement('br');
var regex = /(<br \/>)/g;
return text.split(regex).map(function(line, index) {
return line.match(regex) ? <br key={"key_" + index} /> : line;
});
}
var Text = React.createClass({
render: function() {
return <div>{ breakLine(this.props.content) }</div>;
}
});
React.render(<Text content="Here are some <br /> Lines <br /> to break!" />, document.body);
回答by joemaddalone
You're most likely looking for dangerouslySetInnerHTML. The following code will work without needing the breakLine function.
您很可能正在寻找危险的SetInnerHTML。以下代码无需 breakLine 函数即可工作。
const Text = ({content}) => {
return (
<p dangerouslySetInnerHTML={{__html: content}}></p>
);
};