我想在React Native的Text组件中插入一个新行(如\ r \ n,<br />)。
如果我有:
<text><br />
Hi~<br >
this is a test message.<br />
</text>
然后React Native呈现Hi~ this is a test message.
是否可以渲染文本添加新行,如下所示:
Hi~
this is a test message.
我现在无法测试它但是应该这样做:
<Text>
Hi~{"\n"}
this is a test message.
</Text>
你可以使用``这样:
<Text>{`Hi~
this is a test message.`}</Text>
你可以这样做:
{'创建您的帐户'}
您也可以在渲染方法中将其添加为常量,以便于重用:
render() {
const br = `\n`;
return (
<Text>Capital Street{br}Cambridge{br}CB11 5XE{br}United Kingdom</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-native-new-break-line-example
在文本和css \n
中使用white-space: pre-wrap;
你也可以这样做:
<Text>{`
Hi~
this is a test message.
`}</Text>
在我看来更容易,因为你不必在字符串中插入东西;只需将其包裹一次,它就会保留所有换行符。
使用:
<Text>{`Hi,\nCurtis!`}</Text>
结果:
嗨,
柯蒂斯!
这对我有用
<Text>{`Hi~\nthis is a test message.`}</Text>
(反应原生0.41.0)
您可以使用{'\n'}
作为换行符。嗨〜{'\ n'}这是一条测试信息。
如果您要显示状态变量的数据,请使用此选项。
<Text>{this.state.user.bio.replace('<br/>', '\n')}</Text>
你可以尝试这样使用
<text>{`${val}\n`}</text>
更好的是:如果你使用styled-components
,你可以这样做:
import React, { Component } from 'react';
import styled from 'styled-components';
const Text = styled.Text`
text-align: left;
font-size: 20px;
`;
export default class extends Component {
(...)
render(){
return (
<View>
<Text>{`
1. line 1
2. line 2
3. line 3
`}</Text>
</View>
);
}
}