android - 如何在 React Native 中全局声明字符串

标签 android string react-native

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

React Native 应用程序的方法是声明字符串。我在有 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>

最佳答案

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>

关于android - 如何在 React Native 中全局声明字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43603248/

相关文章:

android - 使可点击的布局膨胀?

python - Pandas 数据框中的条件分组

javascript - 可能的未处理的 Promise 拒绝 - React-Native with Firebase

android - 通过设备同步 SQLite 表

java - ANDROID - 如何保存字符串并从任何应用程序访问它

string - 我如何找到像自动完成这样的最短文本?

c++ - 如何使用迭代器?

react-native - React Native Admob 库崩溃并且 gradle 无法构建

javascript - React Native Expo AV - 音频不播放

java - 安全性 - 如何在 android 应用程序中实现用户之间的阻止功能,使他们无法再相互联系