我想在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>
Hi~{"\n"}
this is a test message.
</Text>
其他回答
最干净和最灵活的方法之一是使用模板字面量。
使用它的一个优点是,如果你想在文本体中显示字符串变量的内容,它更干净和直接。
(请注意使用反引号)
const customMessage = 'This is a test message';
<Text>
{`
Hi~
${customMessage}
`}
</Text>
会导致
Hi~
This is a test message
这对我很有效
<Text>{`Hi~\nthis is a test message.`}</Text>
(react-native 0.41.0)
简单使用反勾号(es6特性)
解决方案1
const Message = 'This is a message';
<Text>
{`
Hi~
${Message}
`}
</Text>
解决方案2在文本中添加“\n”
<Text>
Hi~{"\n"}
This is a message.
</Text>
下面是一个使用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>
显示:
我需要一个在三元运算符中分支的单行解决方案,以保持我的代码很好地缩进。
{foo ? `First line of text\nSecond line of text` : `Single line of text`}
Sublime语法高亮显示有助于突出显示换行字符: