繁体   English   中英

新行反应

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM