为了账号安全,请及时绑定邮箱和手机立即绑定

如何设置可以在样式中使用的变量

如何设置可以在样式中使用的变量

LEATH 2023-06-04 17:10:43
我正在使用 React 本机组件,根据其支持,它使用两种主要颜色。因为我想在样式表中访问该变量,所以我在类之外声明它,而不是在状态中。首先,我将其声明为蓝色,然后在构造函数中将其值更改为绿色。但是它使用的文本仍然是蓝色的。我知道它与渲染有关,但我认为因为我更改了生命周期中第一个类构造函数中的值,所以它会起作用。我不想在 JSX 样式标签中使用函数,那么有解决方案吗?let mainColor = Colors.blue1;export default class Article extends Component {    constructor(props) {        super(props);        mainColor = Colors.green;        this.state={            liked: false,            withHeroImage: false        }    }    render() {        return (           <Text style={styles.title}>Lorem ipsum</Text>        );    }}const styles = StyleSheet.create({    title:{        fontSize: 20,        color: mainColor,        fontFamily: FontFamily.PoppinsSemibold,        marginBottom: 20    }})
查看完整描述

3 回答

?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

我不认为您可以在创建后修改样式表,并且不清楚您为什么要这样做。

在您的示例中,您可以只向标签添加一个动态属性Text,如下所示:

<Text style={[styles.title, {color:mainColor}]}>Lorem ipsum</Text>


查看完整回答
反对 回复 2023-06-04
?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

 let mainColor = Colors.blue1;


export default class Article extends Component {


  constructor(props) {

    super(props);

    this.state={

        liked: false,

        withHeroImage: false,

        mainColor = Colors.green;

    }

}


render() {

    return (


       <Text style={[styles.title, color: this.state.mainColor]}>Lorem ipsum</Text>

    );

}}


  const styles = StyleSheet.create({

title:{

    fontSize: 20,

    fontFamily: FontFamily.PoppinsSemibold,

    marginBottom: 20

}

})

试试这个方法。只是更新变量不会做任何改变。在渲染部分进行更改应该在 setState 或 props 中完成。所以如果你想更新颜色,那么在 setState 中获取颜色并将其分配给样式,就像上面所做的那样。希望能帮助到你 !!!!


查看完整回答
反对 回复 2023-06-04
?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

如果你的React版本是16.8或更高,你可以使用效果hook

用法

import React, { useState, useEffect } from 'react';

import { Text, View, StyleSheet,Button } from 'react-native';



export default function Article() {

  const [maincol, setColor] = useState("blue");


  const styles = StyleSheet.create({

    title:{

        fontSize: 20,

        color: maincol,

        marginBottom: 20

    }

})


  useEffect(() => {

    console.log(maincol);

  });


        return (

          <View style={{flex:1,justifyContent:"center",alignItems:"center"}}>

           <Button title="change color" onPress={() => setColor("green")} />

           <Text style={styles.title}>Lorem ipsum</Text>

           </View>

        );

}


查看完整回答
反对 回复 2023-06-04
  • 3 回答
  • 0 关注
  • 118 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信