React Native 如何使用样式道具

React Native how to use styles 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 属性中使用 style={styles.backgroundColorTheme} 而不是 style={styles(this.props).backgroundColorTheme}

有常量样式:

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

你有很多可能性:

  1. Stylesheet.flatten(样式数组)的用法
<List 
    style={StyleSheet.flatten([
          styles.backgroundColorTheme, 
          {backgroundColor: 'yourcolor'}
    ]}
>
   ...
</List>
  1. return您的风格
  2. 的功能
const getListStyle = color => ({
   backgroundColor: color,
});
...
<List 
    style={getListStyle(color)}
>
   ...
</List>
  1. 对我来说最好的是使用styled-components
import styled from 'styled-components';

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

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

在渲染 return 之前的 SettingsView 组件中,写入 const themedStyles = styles(this.props);。然后你可以使用 style={themedStyles.backgroundColorTheme}.