Search code examples
reactjsreact-nativereact-props

React Native how to use styles props


There is my SettingsView Component:

<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>

How in style attribute I can use style={styles.backgroundColorTheme} instead of style={styles(this.props).backgroundColorTheme}

There is const styles:

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,
    }
});

Solution

  • You have a lot of possibilities:

    1. Usage of Stylesheet.flatten(Array of styles)
    <List 
        style={StyleSheet.flatten([
              styles.backgroundColorTheme, 
              {backgroundColor: 'yourcolor'}
        ]}
    >
       ...
    </List>
    
    1. A function that return your style
    const getListStyle = color => ({
       backgroundColor: color,
    });
    ...
    <List 
        style={getListStyle(color)}
    >
       ...
    </List>
    
    1. The best for me is to use styled-components
    import styled from 'styled-components';
    
    const ThemeColoredList = styled(List)`
       background-color: ${props => props.backgroundColor || 'yourdefaultcolorhere'}
    `;
    
    const Page = () => (
       <ThemeColoredList backgroundColor='yourcolorhere'>
          ...
       </ThemeColoredList>
    );