我想在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.
当前回答
这段代码适用于我的环境。(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
其他回答
Use:
<Text>{`Hi,\nCurtis!`}</Text>
结果:
你好, 柯蒂斯!
这应该做到:
<Text>
Hi~{"\n"}
this is a test message.
</Text>
只需在Text标签中放入{'\n'}
<Text>
Hello {'\n'}
World!
</Text>
可以使用{'\n'}作为换行符。 嗨~ {'\n'}这是一个测试消息。
在数组中定义的文本行之间插入<br>的另一种方法:
import react, { Fragment } from 'react';
const lines = [
'One line',
'Another line',
];
const textContent =
lines.reduce(items, line, index) => {
if (index > 0) {
items.push(<br key={'br-'+index}/>);
}
items.push(<Fragment key={'item-'+index}>{line}</Fragment>);
return items;
}, []);
然后文本可以作为变量使用:
<Text>{textContent}</Text>
如果不可用,Fragment可以这样定义:
const Fragment = (props) => props.children;