我可以在React Native中创建动态样式吗? [英] Can I make dynamic styles in React Native?
本文介绍了我可以在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 style={jewelStyle()} />
...
jewelStyle = function(options) {
return {
borderRadius: 10,
background: randomColor(),
}
}
每次渲染视图时,将使用与其关联的随机颜色来实例化新的样式对象。当然,这意味着颜色将在每次组件被重新渲染时改变,这可能不是你想要的。您可以这样做:
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中创建动态样式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文