我想在React Native的文本组件中插入一个新行(如\r\n,
)。
如果我有
<text><br />
Hi~<br >
this is a test message.<br />
</text>
那么React Native就会渲染 "Hi~这是一条测试信息"。
是否可以像这样渲染文本,添加新的一行。
Hi~
this is a test message.
这应该可以了。
<Text>
Hi~{"\n"}
this is a test message.
</Text>
你可以使用{'\n'}
作为换行符。
更好的是,如果你使用 "styled-components",你可以做这样的事情: 如果你使用 "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>
);
}
}
我需要一个单行解决方案,在三元操作符中进行分支,以使我的代码保持良好的缩进。
{foo ? `First line of text\nSecond line of text` : `Single line of text`}
崇高的语法高亮有助于突出显示断行字符。
[! [崇高语法高亮][1]][1]
如果有人想为数组中的每一个字符串添加一行新的字符串,你可以这样做。
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。
我'用的是react js。 以上答案对我来说都不适用,但结合起来就可以了。 在native上应该也能用。 下面的代码。
//react js
<div style={{ whiteSpace: 'pre-wrap' }}>
<text>{`hello \nthere`}</text>
</div>
//native (haven't tested but, technically should work...)
<View style={{ whiteSpace: 'pre-wrap' }}>
<Text>{`hello \nthere`}</Text>
</View