我想在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.
当前回答
如果有人正在寻找一个解决方案,你想要在数组中的每个字符串有一个新的行,你可以这样做:
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
其他回答
Use:
<Text>{`Hi,\nCurtis!`}</Text>
结果:
你好, 柯蒂斯!
https://stackoverflow.com/a/44845810/10480776 @Edison D'souza的答案正是我一直在寻找的。但是,它只是替换字符串的第一次出现。下面是我处理多个<br/>标签的解决方案:
<Typography style={{ whiteSpace: "pre-line" }}>
{shortDescription.split("<br/>").join("\n")}
</Typography>
抱歉,由于声誉评分限制,我无法评论他的帖子。
下面是一个使用TypeScript的React(不是React Native)的解决方案。
同样的概念也适用于React Native
import React from 'react';
type Props = {
children: string;
Wrapper?: any;
}
/**
* Automatically break lines for text
*
* Avoids relying on <br /> for every line break
*
* @example
* <Text>
* {`
* First line
*
* Another line, which will respect line break
* `}
* </Text>
* @param props
*/
export const Text: React.FunctionComponent<Props> = (props) => {
const { children, Wrapper = 'div' } = props;
return (
<Wrapper style={{ whiteSpace: 'pre-line' }}>
{children}
</Wrapper>
);
};
export default Text;
用法:
<Text>
{`
This page uses server side rendering (SSR)
Each page refresh (either SSR or CSR) queries the GraphQL API and displays products below:
`}
</Text>
显示:
对此有两种主要的解决方案。
方法一:只要在下面加上“\n”就可以了
<Text>
First Line {'\n'} Second Line.
</Text>
方法2:在字符串字面量中添加换行符,如下所示。
<Text>
`First Line
Second Line`.
</Text>
要了解更多信息,请参考下面的教程。
https://sourcefreeze.com/how-to-insert-a-line-break-into-a-text-component-in-react-native/
在数组中定义的文本行之间插入<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;