[英]New line in react
我正在嘗試將以下代碼發送到React js中的子組件:
{
carPhoto: "../../images/small-logo.jpg",
make: "Mercedes",
price: "€20000",
desc: "Vivamus gravida magna massa in cursus mi"
}
現在,我試圖將desc分為兩行。 我嘗試使用\\ 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"
但是沒有任何效果。 有什么建議嗎?
<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"} />
您可以按照注釋中的建議使用CSS。 或者您可以使用<br/>
標記危險地設置內部HTML :
<div dangerouslySetInnerHTML={{__html: this.props.desc}} />
重要的是要注意,這種方法容易產生XSS,因此得名。
您可以在這里閱讀更多信息: https : //facebook.github.io/react/tips/dangerously-set-inner-html.html
在react中進行空格或換行的簡單方法是使用如下方式創建模塊:(並且不要忘記添加空格:pre或pre-wrap;用於容器)
// htmlCodes.js
export const nbsp = '\u00A0';
export const breakline = '\u000A';
然后在組件或字符串中使用它:
// 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>
}
最好的方法是,創建組件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.