目前我正在使用 I18nManager
将 LTR 更改为 RTL
,但它只有在重新启动应用程序后才能工作,我的代码如下所示
import {I18nManager} from 'react-native';
import RNRestart from 'react-native-restart';
changeLtrToRtl=()=>{
I18nManager.forceRTL(true);
RNRestart.Restart();
}
是否有其他方法可以在不重启应用的情况下实现 LTR 到 RTL 的更改?
最佳答案
您可以使用 Context API 来设置应用程序的方向并使用来自子组件的值。使用该值,您可以有条件地更改组件的方向。
// using I18nManager you can get initial direction of device or you can use async storage or both of them as combined. i really dont care now...
const LanguageDirectionContext = createContext({
direction: 'ltr'
})
const LanguageDirectionProvider = ({ children }) => {
const [direction, setDirection] = useState('ltr')
const toggleDirection = () => {
setDirection(direction === 'ltr' ? 'rtl' : 'ltr')
}
useEffect(() => {
// use I18nManager to force direction and use asyncstorage to save the current direction to device.
}, [direction])
return (
<LanguageDirectionContext.Provider value={{
direction,
toggleDirection
}}>
{children}
</LanguageDirectionContext.Provider>
)
}
创建方向依赖组件并用我们创建的提供者包装它。在该上下文中使用钩子(Hook)也是一种很好的做法。检查一下。
const useDirection = () => {
const context = useContext(LanguageDirectionContext)
if (!context) {
throw new Error('You forgot the language provider!')
}
return context
}
方向相关的文本组件示例。
const MyCustomTextComponent = ({ children, style, ...rest }) => {
const { direction } = useDirection()
// i cant understand that the direction of text correct right now. maybe you dont need textAlign property.
return <Text style={[style, { writingDirection: direction, textAlign: direction === 'ltr' ? 'left' : 'right' }]} {...rest}>{children}</Text>
}
如果您有任何其他需要方向的组件,您可以使用 useDirection Hook 重新创建这些组件。
现在您可以使用 toggleDirection 函数来更改组件的方向。
const MyDirectionChangerButton = () => {
const { toggleDirection } = useDirection()
return (
<Button title="Change direction." onPress={toggleDirection} />
)
}
这里是完整的例子:https://snack.expo.io/@kubilaysali/frowning-waffles
关于android - 在不重新启动应用程序的情况下将 native 应用程序 LTR 更改为 RTL 更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62768878/