反应中的新行
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
相关文章:
- 如何从rails中的代码中删除新行( )
- 拆分文本以每隔n个字符添加一行新行,并注意空格
- 如何在脚本上添加新行
- 在不刷新整个网格的情况下,向Asp.net网格视图添加新行
- 字符串中的
标记未正确在 HTML 中创建新行 - JavaScript-如果以前不存在文本,如何从文本区域删除新行
- 反应中的新行
- 阻止ReSharper将JavaScript函数参数放到新行中
- HTML表内容:如果行很长,如何在新行中显示部分内容
- dhtmlx添加新行并启动单元格编辑器
- 将新行打印到$mdToast
- 在新行(html)中动态添加更多文本字段
- 使用删除文本创建新行
- 如何在Google Geochart图表的工具提示文本中添加新行
- NodeJS Fork-每次子流程发送新行时都进行React
- 为什么要将此p标记添加为新行
- 如何转义php中的新行字符以输出为javascript字符串值
- 在Aptana Studio 3中将Javascript数组自动格式化为新行
- Jquery在表WITH函数中追加新行后添加单击事件
- 无法编辑添加的新行