亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何設置可以在樣式中使用的變量

如何設置可以在樣式中使用的變量

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 中獲取顏色并將其分配給樣式,就像上面所做的那樣。希望能幫助到你 ?。。。?/p>


查看完整回答
反對 回復 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 關注
  • 203 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號