如何在StyleSheet.create中获取对象?(React Native)

时间:2016-06-20 08:47:27

标签: javascript reactjs react-native

const styles = StyleSheet.create({

    container : {
        flex : 1,
        backgroundColor : config.getColor('bg'),
    },
    title : {
        marginLeft : 80,
        marginTop : 30,
        height : 35,
        width : 100,
        borderRadius : 17,
        borderWidth : 1,
        borderColor : config.getColor('theme'),
        fontSize : 17,
        color : config.getColor('theme')
    }
});

当我在console.log styles.title时,我得到了一个数字。那么如何将它转换为对象呢?

2 个答案:

答案 0 :(得分:16)

您可以使用flatten方法。

示例:

StyleSheet.flatten(styles.title)

答案 1 :(得分:2)

Jean的回答非常好。但是我每次都使用这种模式不重复StyleSheet.flatten

import { StyleSheet } from 'react-native'

const styles = StyleSheet.create({
    container: {
        flex: 1,
        display: 'flex',
        justifyContent: 'space-between',
        padding: 20,
    },
})

export default Object.keys(styles).reduce((newObject, key) => ({ 
  ...newObject, 
  [key]: StyleSheet.flatten(styles[key]) 
}), {})