android - 在不重新启动应用程序的情况下将 native 应用程序 LTR 更改为 RTL 更改

标签 android ios reactjs react-native

目前我正在使用 I18nManagerLTR 更改为 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/

相关文章:

android - 文件 0000000000000001.db 是什么?

android - 无法使用 iframe 标签在 WebView 内播放视频?

ios - UICollectionView 照片库到全屏

reactjs - 如何将 redux 连接到非默认组件

javascript - 错误 : querySrv ENOTFOUND _mongodb. _tcp.cluster0.kspub.mongodb.net

javascript - 从外部 API 为 React 组件绑定(bind)数据

android - 是否可以在网络上运行 eclipse IDE,以便其他用户可以与您一起工作?喜欢谷歌文档?

java - 回收器 View 无限滚动无法正常工作

android - Google 的 G Suite 应用程序如何共享数据?

ios - MKDirections 不在 iOS map 上显示路线