React Native如何使用样式道具

时间:2019-10-20 20:06:22

标签: reactjs react-native react-props

有我的SettingsView组件:

<List style={styles(this.props).backgroundColorTheme}>
            <ListItem style={custom.settingsListItem} onPress={() => this.props.navigation.navigate('AppIntro')}>
              <MaterialIcons name="import-contacts" size={25} color={'#22364F'}/>
              <Text style={custom.settingsText}>
                  Покажете въвеждащата страница
              </Text>
              <Entypo name="chevron-right" size={25} style={custom.settingsDetailsArrow}/>
            </ListItem>
</List>

如何在样式属性中使用style = {styles.backgroundColorTheme}代替style = {styles(this.props).backgroundColorTheme}

有const样式:

import {StyleSheet} from "react-native";

export const styles = (props) => StyleSheet.create({
    colorTheme: {
        color: props.theme.backgroundColor,
        marginTop: 60,
        marginBottom: 20,
        marginLeft: 20,
        fontWeight: '200',
        fontSize: 24,
    },
    backgroundColorTheme: {
        backgroundColor: props.theme.backgroundColor,
    }
});

2 个答案:

答案 0 :(得分:0)

您有很多可能性:

1)Stylesheet.flatten(样式数组)的用法

<List 
    style={StyleSheet.flatten([
          styles.backgroundColorTheme, 
          {backgroundColor: 'yourcolor'
    }]}
>
   ...
</List>

2)一个返回样式的函数

const getListStyle = color => ({
   backgroundColor: color,
});
...
<List 
    style={getListStyle(color)}
>
   ...
</List>

3)对我来说最好的是使用styled-components

import styled from 'styled-components';

const ThemeColoredList = styled(List)`
   background-color: ${props => props.backgroundColor || 'yourdefaultcolorhere'}
`;

const Page = () => (
   <ThemeColoredList backgroundColor='yourcolorhere'>
      ...
   </ThemeColoredList>
);

答案 1 :(得分:0)

在您从渲染返回之前,在SettingsView组件中,编写const themedStyles = styles(this.props);。然后,您可以使用style={themedStyles.backgroundColorTheme}