我想在React Native的文本组件中插入一个新行(如\r\n, <br />)。
如果我有:
<text>
<br />
Hi~<br />
this is a test message.<br />
</text>
然后React Native渲染Hi~这是一个测试消息。
它是可能的渲染文本添加一个新的行像这样:
Hi~
this is a test message.
我想在React Native的文本组件中插入一个新行(如\r\n, <br />)。
如果我有:
<text>
<br />
Hi~<br />
this is a test message.<br />
</text>
然后React Native渲染Hi~这是一个测试消息。
它是可能的渲染文本添加一个新的行像这样:
Hi~
this is a test message.
当前回答
编辑:
如果你使用模板字面值(参见<Text>元素),你也可以像这样添加换行符:
import React, { Component } from 'react';
import { Text, View } from "react-native";
export default class extends Component {
(...)
render(){
return (
<View>
<Text>{`
1. line 1
2. line 2
3. line 3
`}</Text>
</View>
);
}
}
其他回答
如果您要显示来自状态变量的数据,请使用此方法。
<Text>{this.state.user.bio.replace('<br/>', '\n')}</Text>
我使用p标签的新行。这里我粘贴了代码,这对大家都有帮助。
const new2DArr = associativeArr.map((crntVal )=>{
return <p > Id : {crntVal.id} City Name : {crntVal.cityName} </p>;
});
这应该做到:
<Text>
Hi~{"\n"}
this is a test message.
</Text>
这段代码适用于我的环境。(react-native 0.63.4)
const charChangeLine = `
`
// const charChangeLine = "\n" // or it is ok
const textWithChangeLine = "abc\ndef"
<Text>{textWithChangeLine.replace('¥n', charChangeLine)}</Text>
结果
abc
def
React不喜欢你把HTML <br />放在它需要文本的地方,而且\ns并不总是被渲染,除非在<pre>标记中。
也许可以像这样将每个断行字符串(段落)包装在<p>标记中:
{text.split("\n").map((line, idx) => <p key={idx}>{line}</p>)}
如果你在迭代React组件,不要忘记键。