我想在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标签中放入{'\n'}
<Text>
Hello {'\n'}
World!
</Text>
其他回答
如果有人正在寻找一个解决方案,你想要在数组中的每个字符串有一个新的行,你可以这样做:
import * as React from 'react';
import { Text, View} from 'react-native';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
description: ['Line 1', 'Line 2', 'Line 3'],
};
}
render() {
// Separate each string with a new line
let description = this.state.description.join('\n\n');
let descriptionElement = (
<Text>{description}</Text>
);
return (
<View style={{marginTop: 50}}>
{descriptionElement}
</View>
);
}
}
请参阅小吃现场示例:https://snack.expo.io/@cmacdonnacha/react- nativenew -break-line-example
只需在Text标签中放入{'\n'}
<Text>
Hello {'\n'}
World!
</Text>
这应该做到:
<Text>
Hi~{"\n"}
this is a test message.
</Text>
在文本和css空格中使用\n: pre-wrap;
最干净和最灵活的方法之一是使用模板字面量。
使用它的一个优点是,如果你想在文本体中显示字符串变量的内容,它更干净和直接。
(请注意使用反引号)
const customMessage = 'This is a test message';
<Text>
{`
Hi~
${customMessage}
`}
</Text>
会导致
Hi~
This is a test message