React Native set文本方向为RTL(非自动)

时间:2018-01-24 12:48:30

标签: react-native

我有一些动态加载文本的Text元素。这是一个与一些英语混合的RTL语言(希伯来语)文本。

  1. 当第一个字符为英语时,它会自动设置为LTR方向。
  2. 当第一个字符为希伯来语时,它会自动设置为RTL方向。
  3. 我对这种行为不满意!

    无论如何我想将元素设置为RTL。总是

    在CSS中非常简单: text-align: right; direction: rtl;

    如何在React Native中实现相同的目标?

2 个答案:

答案 0 :(得分:0)

我这样做是:

textAlign:'right'

您的文字应具有这种样式。

答案 1 :(得分:0)

当我遇到这个问题时,我使用 Unicode 方向字符(它们是引号之间的不可见字符)来处理它:

这些会改变您所看到的行为,明确说明应该如何处理文本而不是让系统假设。

如何应用这些取决于您。我主要是在源内容中使用正则表达式查找替换插入来做到这一点,但是您可以执行类似的操作(未经测试),对 useTranslationt 函数进行换行替换来包装文本在适当的 Unicode 控制字符中:

import { I18nManager } from 'react-native'
// assuming you're using i18n hooks
import { useTranslation } from 'react-i18next'

const rtlMarkerChar = '‏'
const ltrMarkerChar = '‎'
const directionChar = I18nManager.isRTL ? rtlMarkerChar : ltrMarkerChar

// Use instead of `useTranslation` to force text right on RTL and left on LTR
// regardless of the initial character of the particular snippet of text
export const useLocaleAlignedText = () => {
  const { t } = useTranslation()
  // I can't remember if you need them at the start and end or just the start...
  return (key) => `${directionChar}${t(key)}${directionChar}`
}

// For example, this should be consistently RTL or LTR regardless of content
const SomeComponent = ({ contentKey }) => {
  const t = useLocaleAlignedText()
  return <Text>{t(contentKey)}</Text>
}

请注意,当您的内容包含换行符时,上述内容可能不起作用,您可能需要在每一行的开头注入控制字符(我认为这可能是我选择将字符注入的原因之一)源材料,但也请注意,这是一项艰苦的工作,很容易出错)。

相关问题