Reactjs 反应本地动态样式

Reactjs 反应本地动态样式,reactjs,react-native,Reactjs,React Native,我正在创建s crypto应用程序,我想在价格下跌时将背景颜色更改为红色,在价格上涨时将背景颜色更改为绿色,然后在2秒钟后使用setTimeout将背景更改回正常 我尝试了两种不同的方法来至少改变背景颜色,但在这两种情况下,我都得到了以下错误 您试图使用值#ffe5e5设置键backgroundColor 在一个不可变且已冻结的对象上 我问了一个问题,但出于某种原因,我得到的答复并不令人信服 之后,我尝试了一种不同的方法(不允许使用样式表的方法),但仍然得到了相同的错误 我把我的新代码放在这里(

我正在创建s crypto应用程序,我想在价格下跌时将背景颜色更改为红色,在价格上涨时将背景颜色更改为绿色,然后在2秒钟后使用setTimeout将背景更改回正常

我尝试了两种不同的方法来至少改变背景颜色,但在这两种情况下,我都得到了以下错误

您试图使用值#ffe5e5设置键backgroundColor 在一个不可变且已冻结的对象上

我问了一个问题,但出于某种原因,我得到的答复并不令人信服

之后,我尝试了一种不同的方法(不允许使用样式表的方法),但仍然得到了相同的错误

我把我的新代码放在这里(你可以参考问题中我以前的代码)

首先,我在全局范围内声明了一个对象,如下所示

var upperRow = {
    display: "flex",
    flexDirection: "row",
    marginBottom: 5, 
    backgroundColor: "white"
} 


class  CoinCard extends Component {
  componentWillReceiveProps(nextProps) {

    if (this.props.coinPrice != nextProps.coinPrice ) {
       if (this.props.coinPrice > nextProps.coinPrice) {

           upperRow["backgroundColor"] = "#ffe5e5";
 }
}
return (

    <View style={container}>

            <View style={upperRow}>
然后我试着像这样改变背景色

var upperRow = {
    display: "flex",
    flexDirection: "row",
    marginBottom: 5, 
    backgroundColor: "white"
} 


class  CoinCard extends Component {
  componentWillReceiveProps(nextProps) {

    if (this.props.coinPrice != nextProps.coinPrice ) {
       if (this.props.coinPrice > nextProps.coinPrice) {

           upperRow["backgroundColor"] = "#ffe5e5";
 }
}
return (

    <View style={container}>

            <View style={upperRow}>
然后像这样指定样式

var upperRow = {
    display: "flex",
    flexDirection: "row",
    marginBottom: 5, 
    backgroundColor: "white"
} 


class  CoinCard extends Component {
  componentWillReceiveProps(nextProps) {

    if (this.props.coinPrice != nextProps.coinPrice ) {
       if (this.props.coinPrice > nextProps.coinPrice) {

           upperRow["backgroundColor"] = "#ffe5e5";
 }
}
return (

    <View style={container}>

            <View style={upperRow}>
返回(

[问题:如何动态更改样式?

无论您的硬币最近是否减少,您都需要保持状态。 想象一下这种形状的状态:

state = {
  hasIncreased: boolean,
  hasDecreased: boolean,
}
现在,您可以在
组件WillReceiveProps
中更改此状态(但现在已弃用,因此如果您使用的是16.3或更高版本,可能会逐步淘汰它),如下所示:


你应该尽量避免以一种易变的方式更改样式。关键是你的状态应该反映你显示的内容。

只是想知道,有什么原因它是
CoinCard
之外的一个变量吗?@Dan没有具体的原因,可能是为了让事情顺利进行而进行的一次糟糕的编码实践。很好的答案,ju有一件事我无法理解你在这里的意思,
上排,增加了&&{backgroundColor:'green'},减少了&{backgroundColor:'red'},
就像
增加了&&{backgroundColor:'green'},减少了&{backgroundColor:'red'},
(这可能是一个三元表达式,但为什么要&&
{backgroundColor:'red'}
这确实是一个三元表达式。我们要做的是,如果
hasEngress
为真,返回包含绿色背景的样式。如果
hasDegress
为真,我们要返回包含红色背景的样式。我喜欢使用三元表,因为它很简洁,对我来说仍然非常可读。Si由于
style
属性也采用了一系列样式,至少对我来说这似乎是最简单的方法。谢谢champ,即使我非常喜欢三元表达式,但我始终认为我们需要为它们提供类似这样的条件
this.state.increased?{backgroundColor:“green”}:{backgroundColor:“white”},
我指的是这部分:
{backgroundColor:“white”},
True。通常,如果你要使用一个类似于这样的短手条件,你会使用
条件?if:else
。我想我把它错误地标记为三元表达式,而它只是在使用运算符。当写
值和值2
时,如果第一个值为True,它会返回第二个值,否则它会返回第一个值。基本上我是使用
&&
运算符(可以使用
|
进行反向运算)来生成更短的if语句。如果它看起来有点陌生,可以定义一个类方法,通过一个完整的
if
-语句返回您需要的任何内容!