【问题标题】:How to declare strings globally in react native如何在本机反应中全局声明字符串
【发布时间】:2017-09-22 00:42:53
【问题描述】:

我的react-native 应用程序中有很多字符串。我看到一些字符串在多个地方使用。 IMO 我不想在我的代码中硬编码字符串,因为这不是好方法。如果项目规模较大,可能需要很长时间才能在多个位置更改相同的字符串。

什么方法是声明反应本机应用程序的字符串。我在有strings.xml的地方做android开发

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string
        name="string_name"
        >text_string</string>
</resources>

我在 JS 文件中做什么。

<Text style={{ fontSize: 22, textAlign: "center" }}>
  Never forget to stay in touch with the people that matter to you.
</Text>

【问题讨论】:

  • 你可以有一个常量对象,你可以在任何需要这些字符串的地方导入
  • @MotiAzu 你能用sn-p的代码解释一下吗?

标签: android string react-native


【解决方案1】:

React Native 中没有专门的字符串资源管理器,就像您在 Android 中那样。 您可以导出包含所有这些常量的文件,并将它们导入到您需要的任何地方。 大致如下:

**** constants.js

export const NeverForget = 'Never forget to stay in touch with the people that matter to you.';
export const OtherString = 'Welcome to the app';

**** Usage:

import { NeverForget } from 'app/constants';

...
<Text style={{ fontSize: 22, textAlign: "center" }}>
  { NeverForget }
</Text>

**** Or

import * as constants from 'app/constants';

...
<Text style={{ fontSize: 22, textAlign: "center" }}>
  { constants.NeverForget }
</Text>

【讨论】:

    【解决方案2】:

    https://github.com/AlexanderZaytsev/react-native-i18n

    我个人会使用这个库来为您的全局字符串设置管理器,因为如果您的应用程序可扩展,它具有在以后控制翻译的额外好处。设置也很简单。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 2015-06-19
    • 2017-10-22
    • 1970-01-01
    • 2018-11-12
    相关资源
    最近更新 更多