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

我正在使用 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

    }

})


LEATH
浏览 125回答 3
3回答

鸿蒙传说

我不认为您可以在创建后修改样式表,并且不清楚您为什么要这样做。在您的示例中,您可以只向标签添加一个动态属性Text,如下所示:<Text&nbsp;style={[styles.title,&nbsp;{color:mainColor}]}>Lorem&nbsp;ipsum</Text>

凤凰求蛊

&nbsp;let mainColor = Colors.blue1;export default class Article extends Component {&nbsp; constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state={&nbsp; &nbsp; &nbsp; &nbsp; liked: false,&nbsp; &nbsp; &nbsp; &nbsp; withHeroImage: false,&nbsp; &nbsp; &nbsp; &nbsp; mainColor = Colors.green;&nbsp; &nbsp; }}render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp;<Text style={[styles.title, color: this.state.mainColor]}>Lorem ipsum</Text>&nbsp; &nbsp; );}}&nbsp; const styles = StyleSheet.create({title:{&nbsp; &nbsp; fontSize: 20,&nbsp; &nbsp; fontFamily: FontFamily.PoppinsSemibold,&nbsp; &nbsp; marginBottom: 20}})试试这个方法。只是更新变量不会做任何改变。在渲染部分进行更改应该在 setState 或 props 中完成。所以如果你想更新颜色,那么在 setState 中获取颜色并将其分配给样式,就像上面所做的那样。希望能帮助到你 !!!!

慕尼黑8549860

如果你的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>        );}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java