2016-04-14 49 views
0

我在學習react-native並提出了一個問題。我正在遵循一個教程系列,但可能錯過了一些東西。我試圖爲不同的組件使用不同的樣式文件,但樣式似乎不適用。
下面是代碼的片段:針對不同組件的不同樣式文件

index.ios.js

import React, { 
    AppRegistry, 
    Component, 
    Text, 
    View, 
    StatusBar 
} from 'react-native'; 

StatusBar.setBarStyle('light-content'); 

class iTunesBrowser extends Component { 
    render() { 
    return (
     <View style={styles.global.mainContainer} > 
     <View style={styles.navbar.appearance}> 
     <View style={styles.navbar.button} ></View> 
      <Text style={styles.navbar.title}>iTunesBrowser</Text> 
      <Text style={styles.navbar.button} >Search</Text> 
     </View> 

     <View style={styles.global.content}> 
      <Text> Some Text </Text> 
     </View> 
     </View> 
    ); 
    } 
} 

import styles from './styles'; 

AppRegistry.registerComponent('iTunesBrowser',() => iTunesBrowser); 

styles.js

export default { 
    global: require('./styles/global'), 
    navbar: require('./styles/navbar') 
}; 

風格/ global.js

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

export default StyleSheet.create({ 
    mainContainer: { 
    flex: 1 
    }, 
    content: { 
    flex: 1, 
    backgroundColor: '#ccc' 
    } 
}); 

風格/ navbar.js在指數或在樣式文件時放

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

export default StyleSheet.create({ 
    appearance: { 
    backgroundColor: '#003333', 
    paddingTop: 30, 
    paddingBottom: 10, 
    flexDirection: 'row' 
    }, 
    title: { 
    color: '#FFFFFF', 
    textAlign: 'center', 
    fontWeight: 'bold', 
    flex: 1 
    }, 
    button: { 
    width: 50, 
    color: '#FEFEFE', 
    textAlign: 'center' 
    } 
}); 

的方式工作。

回答

3

我試過你的榜樣,當你使用JS文件,這種模式它的工作原理:

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

var global = StyleSheet.create({ 
    mainContainer: { 
     flex: 1 
    }, 
    content: { 
     flex: 1, 
     backgroundColor: '#ccc' 
    } 
}); 

module.exports = global; 

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

var navbar = StyleSheet.create({ 
    appearance: { 
     backgroundColor: '#003333', 
     paddingTop: 30, 
     paddingBottom: 10, 
     flexDirection: 'row' 
    }, 
    title: { 
     color: '#FFFFFF', 
     textAlign: 'center', 
     fontWeight: 'bold', 
     flex: 1 
    }, 
    button: { 
     width: 50, 
     color: '#FEFEFE', 
     textAlign: 'center' 
    } 
}); 

module.exports = navbar; 
+0

此代碼完美工作。謝謝。 –

+0

不客氣!我很高興! :) – Vikky

1

在React Native中使用組件樣式的典型方法是將StyleSheet的創建保留在組件本身中,而不是在CSS中使用的單獨文件中。這樣,組件,結構和樣式的所有內容都在同一個文件中。

您仍然可以擁有全局樣式表,並在需要時拉入這些樣式,但在Component中保留組件樣式。

有關社區和Facebook如何建議設置組件的樣式檢查出一個很好的例子:http://makeitopen.com/

相關問題