There are two ways to use global variables in RN

1. By importing and exporting files

Create a new constants.js file

const object = {
   website:'http://www.hao123.com',
   name:'好123', }; export default object;

Import files when needed

import constants from './constansts.js'
<Text>{constants.name}</Text>

There is also another way to write the import file

export default {
   website:'http://www.hao123.com',
   name:'好123', };

2. By declaring global variables

Must be declared first, then called.

global.a = 1;
<Text>{a}</Text>

It can also be written specifically in a file.

global.constants = {
   website:'http://www.baidu.com',
   name:'百度',
};

To call the method, the entry file is called once (such as the index.iOS.js file), and it is used globally.

import './constants.js';
<Text>{global.constants.name}</Text>

Quoting the original text :https://blog.csdn.net/u012878818/article/details/75103330

 

Writing a blog is to remember things that I easily forget, and it is also a summary of my work. Articles can be reproduced without copyright. I hope to do my best to be better, and everyone to work hard and make progress together!

If there is any problem, welcome everyone to discuss it together. If there is a problem with the code, please correct me!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325011356&siteId=291194637