[英]New line in react
I'm trying to send following code to a child component in React js: 我正在尝试将以下代码发送到React js中的子组件:
{
carPhoto: "../../images/small-logo.jpg",
make: "Mercedes",
price: "€20000",
desc: "Vivamus gravida magna massa in cursus mi"
}
Now I'm trying to split desc in two lines. 现在,我试图将desc分为两行。 I tried with \\n , \\r , \\r\\n
我尝试使用\\ n , \\ r , \\ r \\ n
desc: "Vivamus gravida magna<br /> massa in cursus mi"
desc: "Vivamus gravida magna\nmassa in cursus mi"
desc: "Vivamus gravida magna\r\nmassa in cursus mi"
But nothing worked. 但是没有任何效果。 Any advice?
有什么建议吗?
<span>
Example #1: <br /> newline
</span>
<span style={{ whiteSpace: 'pre-wrap' }}>
{"Example #2: \r new line or \u000A new line"}
</span>
{/* do not forget add style { white-space: pre-wrap } */}
<Example3 text={"Example #2: \r new line or \u000A new line"} />
You can either use CSS, as suggested in the comments. 您可以按照注释中的建议使用CSS。 Or you can dangerously set inner HTML using the
<br/>
tag: 或者您可以使用
<br/>
标记危险地设置内部HTML :
<div dangerouslySetInnerHTML={{__html: this.props.desc}} />
It's important to note that this approach is XSS-prone, thus the name. 重要的是要注意,这种方法容易产生XSS,因此得名。
You can read more here: https://facebook.github.io/react/tips/dangerously-set-inner-html.html 您可以在这里阅读更多信息: https : //facebook.github.io/react/tips/dangerously-set-inner-html.html
Easy way to do white space or new line in react is create module with it like this: (and do not forget add white-space: pre or pre-wrap; for container) 在react中进行空格或换行的简单方法是使用如下方式创建模块:(并且不要忘记添加空格:pre或pre-wrap;用于容器)
// htmlCodes.js
export const nbsp = '\u00A0';
export const breakline = '\u000A';
and then use it in component or strings: 然后在组件或字符串中使用它:
// MyComponent.jsx
import {nbsp, breakline} from './htmlCodes';
const myString = `one{nbsp}two{breakline}`;
const MyComponent = () => {
<div style={{ whiteSpace: 'pre-wrap' }}>
first{nbsp}second{breakline}third
</div>
}
the best way, create component Text and use their together: 最好的方法是,创建组件Text并一起使用:
// Text.jsx
export const Text = (children) => {
<span style={{ whiteSpace: 'pre-wrap' }}>
{children}
</span>
}
// MyComponent.jsx
import {nbsp, breakline} from './htmlCodes';
import {Text} from './Text.jsx';
const MyComponent = () => {
<div>
<Text>one{nbsp}two{breakline}three</Text>
</div>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.