反应中的新行

New line in react

本文关键字:新行      更新时间:2023-09-26

我正在尝试将以下代码发送到React js中的子组件:

{
    carPhoto: "../../images/small-logo.jpg",
    make: "Mercedes",
    price: "€20000",
    desc: "Vivamus gravida magna massa in cursus mi"
}

现在我尝试将desc拆分为两行。我尝试了''n''r''n''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"} />

在react中创建空白或新行的简单方法是这样创建模块:(不要忘记添加空白:预包装或预包装;对于容器)

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

非常简单的方法,具有非常简单的组件,具有最简单的html输出

你可以像道具一样使用它

<TravelCard
      text={<BreakString
            text={"7 days 'n Friends Reunion'n Historic, Touristy"} >}
/>

<p>
   <BreakString
      text={"7 days 'n Friends Reunion'n Historic, Touristy"} />
</p>

您应该创建的组件:

const BreakString = ({ text }) => {
  const strArr = text.split("'n");
  return (
    <>
      {strArr.map((str, index) => (
        <React.Fragment key={index}>
          {str}
          {index !== str.length - 1 && <br />}
        </React.Fragment>
      ))}
    </>
  );
};

输出

<p>7 days <br> Friends Reunion<br> Historic, Touristy<br></p>

您可以按照注释中的建议使用CSS。或者,您可以使用<br/>标签危险地设置内部HTML:

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

需要注意的是,这种方法倾向于XSS,因此得名。

您可以在此处阅读更多信息:https://facebook.github.io/react/tips/dangerously-set-inner-html.html