简体   繁体   中英

New line in react

I'm trying to send following code to a child component in 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. I tried with \\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. Or you can dangerously set inner HTML using the <br/> tag:

<div dangerouslySetInnerHTML={{__html: this.props.desc}} />

It's important to note that this approach is XSS-prone, thus the name.

You can read more here: 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)

// 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.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>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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