如何在本机反应中全局声明字符串 [英] How to declare strings globally in react native

查看:27
本文介绍了如何在本机反应中全局声明字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a lot of strings in my react-native application. I see some of strings are being used at multiple places. IMO I do not want to hard code strings in my code as this is not good approach. It may takes ages to change same strings on multiple locations if project go on large scale.

什么方法是声明react native应用程序的字符串.我在它有 strings.xml

What approaches is to declare strings of react native application. I do android development where it has strings.xml

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

我在 JS 文件中所做的事情.

What I am doing in JS files.

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

推荐答案

React Native 中没有像 Android 中那样专门用于字符串的资源管理器.您可以导出一个包含所有这些常量的文件,并将它们导入到您需要的任何地方.一些类似的东西:

There is no specialized resource manager for strings in React Native like you have in Android. You can have a file with all these constants exported and import them wherever you need. Something along these lines:

**** 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>

这篇关于如何在本机反应中全局声明字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆