我想在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.
当前回答
我使用p标签的新行。这里我粘贴了代码,这对大家都有帮助。
const new2DArr = associativeArr.map((crntVal )=>{
return <p > Id : {crntVal.id} City Name : {crntVal.cityName} </p>;
});
其他回答
在需要换行的地方使用{"\n"}
这应该做到:
<Text>
Hi~{"\n"}
this is a test message.
</Text>
你还可以:
<Text>{`
Hi~
this is a test message.
`}</Text>
在我看来更简单,因为你不需要在字符串中插入东西;只要换行一次,就能保留所有换行符。
最干净和最灵活的方法之一是使用模板字面量。
使用它的一个优点是,如果你想在文本体中显示字符串变量的内容,它更干净和直接。
(请注意使用反引号)
const customMessage = 'This is a test message';
<Text>
{`
Hi~
${customMessage}
`}
</Text>
会导致
Hi~
This is a test message
在数组中定义的文本行之间插入<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;