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