Can I make dynamic styles in React Native?

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

Say I have a component with a render like this:


Where jewelStyle =

  {
    bo         


        
15条回答
  •  无人及你
    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 (
          
            
            
            
          
        );
      }
    }
    

提交回复
热议问题