在不重新启动应用程序的情况下反应本机应用程序从 LTR 到 RTL 的更改

jam*_*mal 6 android ios reactjs react-native

目前我正在使用I18nManager更改LTR to RTL,但它只有在重新启动应用程序后才能工作,我的代码如下

 import {I18nManager} from 'react-native';
 import RNRestart from 'react-native-restart';

changeLtrToRtl=()=>{
    I18nManager.forceRTL(true);
    RNRestart.Restart();
}
Run Code Online (Sandbox Code Playgroud)

是否有其他方法可以在不重新启动应用程序的情况下实现从 LTR 到 RTL 的更改?

小智 9

您可以使用 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>
  )
}
Run Code Online (Sandbox Code Playgroud)

创建方向相关组件并将其与我们创建的提供程序包装在一起。在该上下文中使用钩子也是一个很好的做法。看一下这个。

const useDirection = () => {
  const context = useContext(LanguageDirectionContext)

  if (!context) {
    throw new Error('You forgot the language provider!')
  }

  return context
}
Run Code Online (Sandbox Code Playgroud)

方向相关文本组件示例。

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>
}
Run Code Online (Sandbox Code Playgroud)

如果您有任何其他需要方向的组件,您可以使用 useDirection 钩子重新创建这些组件。

现在您可以使用toggleDirection 函数来更改组件的方向。

const MyDirectionChangerButton = () => {
  const { toggleDirection } = useDirection()
  return (
    <Button title="Change direction." onPress={toggleDirection} />
  )
}
Run Code Online (Sandbox Code Playgroud)

这里是完整的例子:https ://snack.expo.io/@kubilaysali/frowning-waffles