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

编程入门 行业动态 更新时间:2024-10-25 17:24:25
本文介绍了我可以在 React Native 中制作动态样式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个渲染如下的组件:

Say I have a component with a render like this:

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

其中jewelStyle =

Where jewelStyle =

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

如何使背景颜色动态且随机分配?我试过了

How could I make the background colour dynamic and randomly assigned? I've tried

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

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

But this makes all instances of View have the same colour, I want each one to be unique.

有什么建议吗?

推荐答案

我通常会做一些类似的事情:

I usually do something along the lines of:

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

...

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

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

Every time View is rendered, a new style object will be instantiated with a random color associated with it. Of course, this means that the colors will change every time the component is re-rendered, which is perhaps not what you want. Instead, you could do something like this:

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

...

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

更多推荐

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

本文发布于:2023-11-06 14:39:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563968.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:样式   动态   React   Native

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!