Can I make dynamic styles in React Native?

后端 未结 15 2186
别跟我提以往
别跟我提以往 2020-12-12 15:24

Say I have a component with a render like this:


Where jewelStyle =

  {
    bo         


        
相关标签:
15条回答
  • 2020-12-12 16:08

    If you are using a screen with filters for example, and you want to set the background of the filter regarding if it was selected or not, you can do:

    <TouchableOpacity style={this.props.venueFilters.includes('Bar')?styles.filterBtnActive:styles.filterBtn} onPress={()=>this.setFilter('Bar')}>
    <Text numberOfLines={1}>
    Bar
    </Text>
    </TouchableOpacity>
    

    On which set filter is:

    setVenueFilter(filter){
      var filters = this.props.venueFilters;
      filters.push(filter);
      console.log(filters.includes('Bar'), "Inclui Bar");
      this.setState(previousState => {
        return { updateFilter: !previousState.updateFilter };
      });
      this.props.setVenueFilter(filters);
    }
    

    PS: the function this.props.setVenueFilter(filters) is a redux action, and this.props.venueFilters is a redux state.

    0 讨论(0)
  • 2020-12-12 16:09

    Had some issue syntactically. This worked for me

    <Text style={[styles.textStyle,{color: 'red'}]}> Hello </Text>
    
    const styles = StyleSheet.create({
       textStyle :{
          textAlign: 'center',   
          fontFamily: 'Arial',
          fontSize: 16
      }
      });
    
    0 讨论(0)
  • 2020-12-12 16:11

    Yes, you can make dynamic styles. You can pass values from Components.

    First create StyleSheetFactory.js

    import { StyleSheet } from "react-native";
    export default class StyleSheetFactory {
      static getSheet(backColor) {
        return StyleSheet.create({
          jewelStyle: {
            borderRadius: 10,
            backgroundColor: backColor,
            width: 20,
            height: 20,
          }
        })
      }
    }
    

    then use it in your component following way

    import React from "react";
    import { View } from "react-native";
    import StyleSheetFactory from './StyleSheetFactory'
    class Main extends React.Component {
      getRandomColor = () => {
        var letters = "0123456789ABCDEF";
        var color = "#";
        for (var i = 0; i < 6; i++) {
          color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
      };
    
      render() {
        return (
          <View>
            <View
              style={StyleSheetFactory.getSheet(this.getRandomColor()).jewelStyle}
            />
            <View
              style={StyleSheetFactory.getSheet(this.getRandomColor()).jewelStyle}
            />
            <View
              style={StyleSheetFactory.getSheet(this.getRandomColor()).jewelStyle}
            />
          </View>
        );
      }
    }
    
    0 讨论(0)
提交回复
热议问题