2017-05-28 21 views
0

我已將styles.jsapp.js分隔開來構成一個簡單的應用程序。我將圖像資源定義爲全局常量變量。 (對於徽標和配置文件)我也嘗試在styles.js中添加這些不變的圖像資源。但是用我目前的方法和語法,我無法從styles.js中導出這些常量圖像資源,因爲它們沒有在樣式變量包裝器中定義。在反應樣式中定義的導出全局變量js文件

styles.js

'use strict' 

import React, { Component } from 'react'; 
import {StyleSheet} from 'react-native'; 

/* 
    const background_img= require("../../resource/mybackground.png"); 
    I tried to define the resource path here 
*/ 

var styles = StyleSheet.create({ 
    /*Styles Definition*/ 
}); 

export default styles 

app.js

'use strict' 

import React, { Component } from 'react'; 
import { AppRegistry, Text, TextInput, View, Image, 
TouchableOpacity, Alert} from 'react-native'; 
import styles from './styles.js'; 

/*const background= require("../../resource/mybackground.png");*/ 
// I want to move this part to styles.js 


export class LoginScene extends Component { 

    constructor(props) { 
    super(props); 
    } 

    render() { 
    return (
     <Image 
     style={[styles.background, styles.container]} 
     source={background} //I want to replace to styles.background_img 
     resizeMode="cover" 
     ></Image> 
     /*Other view definitions*/ 
    ); 
    } 
} 

export default LoginScene 

我表示,我想我與評論上面的代碼改變。如果我想像上面那樣路由源文件,我應該在styles.js中更改哪些內容,以便可以使用樣式變量包裝器同時導出常量全局變量?

回答

3

您可以將樣式導出爲默認樣式,然後您還可以導出其他可以包含值或對象的變量。

import React, { Component } from 'react'; 
import {StyleSheet} from 'react-native'; 

export const assets = { 
    background: require("../../resource/mybackground.png"), 
} 

var styles = StyleSheet.create({ 
    /*Styles Definition*/ 
}); 

export default styles; 

然後在需要時,你可以導入默認和命名出口:

import styles, { assets } from './styles.js'; 
+0

我明白了,這個工程。所以這意味着我們只能從其他'* .js'文件中導出json對象? –

+0

不完全是,您可以導出變量,常量,函數,類,數組,對象。請記住,每個文件只能使用一個「導出默認值」。查看關於es6模塊的指南:http://exploringjs.com/es6/ch_modules.html – nicokant

+0

這真的很有幫助,值得upvotes和接受。 –