我有一些包含动态加载文本的
- 当第一个字符是英语时,它自动设置为LTR方向。
- 当第一个字符是希伯来语时,它自动设置为RTL方向。
我不喜欢这种行为!
无论如何,我想将该元素设置为RTL。总是。
在CSS中,这非常简单: text-align: right; direction: rtl;
在React Native中,我该如何实现相同的效果?
我有一些包含动态加载文本的
我不喜欢这种行为!
无论如何,我想将该元素设置为RTL。总是。
在CSS中,这非常简单: text-align: right; direction: rtl;
在React Native中,我该如何实现相同的效果?
''
用于强制将文本视为RTL''
用于强制将文本视为LTRuseTranslation
的t
函数的交换替换: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()
return (key) => `${directionChar}${t(key)}`
}
// For example, this should be consistently RTL or LTR regardless of content
const SomeComponent = ({ contentKey }) => {
const t = useLocaleAlignedText()
return <Text>{t(contentKey)}</Text>
}
请注意,以上方法可能无法在内容中包含换行符的情况下正常工作,您可能需要在每行开头注入控制字符。这也是我选择将字符注入源材料的原因之一;但是请注意,这很费力且容易出错。
处理RTL文本,请使用样式alignSelf: 'flex-start'
例如React Native:
<View>
<Text style={styles.headersText}>{headerTitle}</Text>
</View>
StyleSheet.create({ headersText: {
alignSelf: 'flex-start', // <- Here Handle RTL for Text
paddingHorizontal: 16,
paddingTop: 14,
color: 'black',
fontSize: 13,
},
});
<Text style={{alignSelf: "flex-start"}}>your text here</Text>
writingDirection: "rtl"
属性,在Android上使用textAlign: "justify"
属性。例如:import { I18nManager, Text } from "react-native";
<Text style={{
writingDirection: I18nManager.isRTL ? "rtl" : "ltr", //OR "auto"
textAlign: "justify"
}}>
your text here
</Text>
justify
的Android方法中,它不会根据文本语言来对齐,而是根据应用程序的I18nManager.isRTL
敏感性来对齐文本,无论文本是阿拉伯语还是英语,都将使用应用程序的方向状态。它只会根据语言书写方向来对齐文本,与选项1不同。但是对于IOS,您应该编写一个条件来提供动态值,就像上面的示例一样。因此,如果您不想显示混乱的文本,特别是如果您在同一个视图中同时拥有两种语言,即如果您在同一个视图中有两个不同的描述,一个是英语,一个是阿拉伯语,但您希望使两个文本在设计实践中保持相同的文本对齐水平,那么这种方法是首选。:
textAlign:'right'
textAlign:“left”
- 这将使文本靠右对齐。 - Samih A
<Text style={{alignSelf: "flex-start"}}>
{text}
</Text>
顺便说一句,如果你想要在整个项目中强制使用RTL,你可以像这样编写代码,并在主App
组件中运行:
import { I18nManager } from "react-native";
const App = () => {
. . . . . . . .
const rtl = () => {
if (I18nManager.isRTL === false) {
I18nManager.allowRTL(true);
I18nManager.forceRTL(true);
}
};
. . . . . . . .
}
flex: 1
,因为它会使Text
扩展并始终对齐到左侧。 - Ahmed Lotfy