CSS 我可以在 React Native 中制作动态样式吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29363671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I make dynamic styles in React Native?
提问by Pete Thorne
Say I have a component with a render like this:
假设我有一个带有这样渲染的组件:
<View style={jewelStyle}></View>
Where jewelStyle =
其中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,
},
But this makes all instances of View have the same colour, I want each one to be unique.
但这使得 View 的所有实例都具有相同的颜色,我希望每个实例都是独一无二的。
Any tips?
有小费吗?
回答by Jimmie Berg
I usually do something along the lines of:
我通常会按照以下方式做一些事情:
<View style={this.jewelStyle()} />
...
...
jewelStyle = function(options) {
return {
borderRadius: 12,
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:
每次渲染 View 时,都会使用与其关联的随机颜色实例化一个新的样式对象。当然,这意味着每次重新渲染组件时颜色都会改变,这可能不是您想要的。相反,您可以执行以下操作:
var myColor = randomColor()
<View style={jewelStyle(myColor)} />
...
...
jewelStyle = function(myColor) {
return {
borderRadius: 10,
background: myColor,
}
}
回答by diegoprates
Yes you can and actually, you should use StyleSheet.create
to create your styles.
是的,您可以并且实际上,您应该使用它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;
And then:
进而:
<Header title="HOME" style={ {backgroundColor: '#10f1f0'} } />
回答by Carlos Atencio
If you still want to take advantage of StyleSheet.create
and also have dynamic styles, try this out:
如果您仍然想利用StyleSheet.create
并拥有动态样式,请尝试以下操作:
const Circle = ({initial}) => {
const initial = user.pending ? user.email[0] : user.firstName[0];
const colorStyles = {
backgroundColor: randomColor()
};
return (
<View style={[styles.circle, colorStyles]}>
<Text style={styles.text}>{initial.toUpperCase()}</Text>
</View>
);
};
const styles = StyleSheet.create({
circle: {
height: 40,
width: 40,
borderRadius: 30,
overflow: 'hidden'
},
text: {
fontSize: 12,
lineHeight: 40,
color: '#fff',
textAlign: 'center'
}
});
Notice how the style
property of the View
is set as an array that combines your stylesheet with your dynamic styles.
请注意如何将 的style
属性View
设置为将样式表与动态样式组合在一起的数组。
回答by Yogesh Lolusare
Had some issue syntactically. This worked for me
在语法上有一些问题。这对我有用
<Text style={[styles.textStyle,{color: 'red'}]}> Hello </Text>
const styles = StyleSheet.create({
textStyle :{
textAlign: 'center',
fontFamily: 'Arial',
fontSize: 16
}
});
回答by Raining
The easiest is mine:
最简单的是我的:
<TextInput
style={[
styles.default,
this.props.singleSourceOfTruth ?
{ backgroundColor: 'black' }
: { backgroundColor: 'white' }
]}/>
回答by Colin Ramsay
You'll want something like this:
你会想要这样的东西:
var RandomBgApp = React.createClass({
render: function() {
var getRandomColor = function() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
var rows = [
{ name: 'row 1'},
{ name: 'row 2'},
{ name: 'row 3'}
];
var rowNodes = rows.map(function(row) {
return <Text style={{backgroundColor:getRandomColor()}}>{row.name}</Text>
});
return (
<View>
{rowNodes}
</View>
);
}
});
In this example I take the rows array, containing the data for the rows in the component, and map it into an array of Text components. I use inline styles to call the getRandomColor
function every time I create a new Text component.
在此示例中,我采用包含组件中行数据的行数组,并将其映射到一个 Text 组件数组。getRandomColor
每次创建新的 Text 组件时,我都会使用内联样式来调用该函数。
The issue with your code is that you define the style once and therefore getRandomColor only gets called once - when you define the style.
您的代码的问题在于您定义了一次样式,因此 getRandomColor 只被调用一次 - 当您定义样式时。
回答by Cesar Alonso
I know there are several answers, but i think the best and most simple is using a state "To change" is the state purpose.
我知道有几个答案,但我认为最好和最简单的是使用状态“改变”是状态目的。
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
style: {
backgroundColor: "white"
}
};
}
onPress = function() {
this.setState({style: {backgroundColor: "red"}});
}
render() {
return (
...
<View style={this.state.style}></View>
...
)
}
}
}
回答by Hossam Ghareeb
You can bind state value directly to style object. Here is an example:
您可以将状态值直接绑定到样式对象。下面是一个例子:
class Timer extends Component{
constructor(props){
super(props);
this.state = {timer: 0, color: '#FF0000'};
setInterval(() => {
this.setState({timer: this.state.timer + 1, color: this.state.timer % 2 == 0 ? '#FF0000' : '#0000FF'});
}, 1000);
}
render(){
return (
<View>
<Text>Timer:</Text>
<Text style={{backgroundColor: this.state.color}}>{this.state.timer}</Text>
</View>
);
}
}
回答by Rajesh Nasit
Yes, you can make dynamic styles. You can pass values from Components.
是的,您可以制作动态样式。您可以从组件传递值。
First create StyleSheetFactory.js
首先创建 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 (
<View>
<View
style={StyleSheetFactory.getSheet(this.getRandomColor()).jewelStyle}
/>
<View
style={StyleSheetFactory.getSheet(this.getRandomColor()).jewelStyle}
/>
<View
style={StyleSheetFactory.getSheet(this.getRandomColor()).jewelStyle}
/>
</View>
);
}
}
回答by Cem Roso
Using object spread operator "..." worked for me:
使用对象传播运算符“...”对我有用:
<View style={{...jewelStyle, ...{'backgroundColor': getRandomColor()}}}></View>