我正在嘗試根據正在顯示的口袋妖怪的型別更改組件的顏色。我在從 api 檢索 pokemon 的父組件中有這個視圖。pokemonType 變數來自 api。它注冊,我可以 console.log('pokemonType') 記錄口袋妖怪的型別,例如“草”。似乎三元運算子沒有注冊 pokemonType 并直接進入默認值。我寫錯了嗎?
{/* Pokemon Type */}
<View style={[
(pokemonType === 'grass') ? styles.grass : styles.pokemonTypeDefault,
(pokemonType === 'fire') ? styles.fire : styles.pokemonTypeDefault,
(pokemonType === 'water') ? styles.water : styles.pokemonTypeDefault,
(pokemonType === 'bug') ? styles.bug : styles.pokemonTypeDefault,
(pokemonType === 'ghost') ? styles.ghost : styles.pokemonTypeDefault,
(pokemonType === 'rock') ? styles.rock : styles.pokemonTypeDefault,
(pokemonType === 'steel') ? styles.steel : styles.pokemonTypeDefault,
(pokemonType === 'electric') ? styles.electric : styles.pokemonTypeDefault,
]}>
<Text style={styles.pokemonTypeText}>{pokemonType.toUpperCase()}</Text>
</View>
const styles = StyleSheet.create({
grass: {
backgroundColor: '#00FF00',
width: 250,
height: 30,
marginTop: 10,
marginLeft: 80,
borderRadius: 50,
},
fire: {
backgroundColor: '#FFA500',
width: 250,
height: 30,
marginTop: 10,
marginLeft: 80,
borderRadius: 50,
},
}) ..//All the other type styles
pokemonTypeDefault: {
width: 250,
height: 30,
marginTop: 10,
marginLeft: 80,
borderRadius: 50,
backgroundColor: 'blue',
},
非常感謝
uj5u.com熱心網友回復:
問題是您添加了styles.pokemonTypeDefault多次,從而覆寫了您的樣式。
react-native 樣式的作業方式是,當您傳遞一組樣式時,右側的樣式會覆寫先前元素上設定的屬性,在您的示例中,如果 pokemon 型別是草,您的樣式陣列將類似于
[styles.grass, styles.pokemonTypeDefault, styles.pokemonTypeDefault, styles.pokemonTypeDefault, styles.pokemonTypeDefault, styles.pokemonTypeDefault, styles.pokemonTypeDefault, styles.pokemonTypeDefault]
一個更簡單、更清晰的解決方案是創建一個函式來獲取您的樣式。
例如
{/* Pokemon Type */}
<View style={getPokemonTypeStyle(pokemonType)}>
<Text style={styles.pokemonTypeText}>{pokemonType.toUpperCase()}</Text>
</View>
const getPokemonTypeStyle = (pokemonType) => {
switch (pokemonType) {
case 'grass':
return styles.grass
case 'fire':
return styles.fire
case 'water':
return styles.water
case 'bug':
return styles.bug
case 'ghost':
return styles.ghost
case 'rock':
return styles.rock
case 'steel':
return styles.steel
case 'electric':
return styles.electric
default:
return styles.pokemonTypeDefault
}
const styles = StyleSheet.create({
grass: {
backgroundColor: '#00FF00',
width: 250,
height: 30,
marginTop: 10,
marginLeft: 80,
borderRadius: 50,
},
fire: {
backgroundColor: '#FFA500',
width: 250,
height: 30,
marginTop: 10,
marginLeft: 80,
borderRadius: 50,
},
}) ..//All the other type styles
pokemonTypeDefault: {
width: 250,
height: 30,
marginTop: 10,
marginLeft: 80,
borderRadius: 50,
backgroundColor: 'blue',
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/364577.html
標籤:javascript 反应 反应原生
上一篇:如何在另一個陣列中插入一個陣列?
