假设我有一个渲染如下的组件:
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 中制作动态样式吗?
发布评论