我可以在 React Native 中制作动态样式吗?

新手上路,请多包涵

假设我有一个像这样渲染的组件:

 <View style={jewelStyle}></View>

珠宝风格 =

   {
    borderRadius: 10,
    backgroundColor: '#FFEFCC',
    width: 20,
    height: 20,
  },

我怎样才能使背景颜色动态和随机分配?我试过了

  {
    borderRadius: 10,
    backgroundColor: getRandomColor(),
    width: 20,
    height: 20,
  },

但这使得 View 的所有实例都具有相同的颜色,我希望每个实例都是唯一的。

有小费吗?

原文由 Pete Thorne 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

我通常会按照以下方式做一些事情:

 <View style={this.jewelStyle()} />

 jewelStyle = function(options) {
   return {
     borderRadius: 12,
     background: randomColor(),
   }
 }

每次渲染 View 时,都会使用与之关联的随机颜色实例化一个新的样式对象。当然,这意味着每次重新渲染组件时颜色都会发生变化,这可能不是您想要的。相反,您可以执行以下操作:

 var myColor = randomColor()
<View style={jewelStyle(myColor)} />

 jewelStyle = function(myColor) {
   return {
     borderRadius: 10,
     background: myColor,
   }
 }

原文由 Jimmie Berg 发布,翻译遵循 CC BY-SA 4.0 许可协议

是的,您可以而且实际上,您应该使用 StyleSheet.create 来创建您的样式。

 import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View
} from 'react-native';

class Header extends Component {
    constructor(props){
        super(props);
    }

    render() {
        const { title, style } = this.props;
        const { header, text } = defaultStyle;
        const combineStyles = StyleSheet.flatten([header, style]);

        return (
            <View style={ combineStyles }>
                <Text style={ text }>
                    { title }
                </Text>
            </View>
        );
    }
}

const defaultStyle = StyleSheet.create({
    header: {
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#fff',
        height: 60,
        paddingTop: 15,
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 3 },
        shadowOpacity: 0.4,
        elevation: 2,
        position: 'relative'
    },
    text: {
        color: '#0d4220',
        fontSize: 16
    }
});

export default Header;

接着:

 <Header title="HOME" style={ {backgroundColor: '#10f1f0'} } />

原文由 diegoprates 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题