[英]How to conditionally overwrite a style with a different style in React Native?
我有一個 PrimaryButton 元素,它有 3 個變體——主要的、次要的和第三的。 正如您在 Pressable 組件的樣式中看到的那樣,我設置了基於變體的默認樣式,例如 styles[variant] 。 現在,如果按鈕變體是第三個,我還想讓 Pressable 組件的 backgroundColor 在被按下時變為紅色。 我已經可以訪問 isPressed 布爾值,它告訴我是否按下了 Pressable,但是,我無法弄清楚如何將 backgroundColor 更改為紅色,只有當變量是第三級時。
const PrimaryButton = ({ title, variant = 'primary', wide = false, style, ...rest }) => {
const width = wide ? '100%' : undefined;
const textColor = variant === 'primary' ? colors.white : colors.primary600;
return (
<Pressable
style={({ pressed: isPressed }) => [
styles.button,
styles[variant],
{
width,
elevation: isPressed ? 5 : 0,
},
style,
]}
{...rest}
>
</Pressable>
);
};
const styles = StyleSheet.create({
button: {
paddingVertical: 12,
paddingHorizontal: 24,
borderRadius: 100,
borderWidth: 1.5,
justifyContent: 'center',
alignItems: 'center',
alignSelf: 'center',
},
primary: {
backgroundColor: colors.primary600,
borderColor: colors.primary600,
},
secondary: {
backgroundColor: colors.white,
borderColor: colors.primary600,
},
tertiary: {
backgroundColor: 'transparent',
borderColor: 'transparent',
},
text: {
textAlign: 'center',
},
});
看看以下內容是否對您有幫助。 如果沒有,請告訴我出了什么問題。
style = {({ pressed: isPressed }) => [
styles.button,
styles[variant],
{
width,
elevation: isPressed ? 5 : 0,
...(variant === 'tertiary') ? { backgroundColor: 'red' } : {}
},
style,
]}
檢查這個包,對這個東西非常有用。 不再推薦直接在字段級別上的樣式。 https://www.npmjs.com/package/isomorphic-style-loader祝你好運
為了覆蓋組件的樣式,在這種情況下,只有當變量是三元時才將背景顏色更改為紅色,您可以使用三元運算符。
訪問定義的樣式以檢索其他按鈕的背景顏色可能很有用。 為此,您可以使用StyleSheet.flatten
,這樣您就不會覆蓋以前應用的顏色樣式。
style = {
({
pressed: isPressed
}) => [
styles.button,
styles[variant],
{
width,
elevation: isPressed ? 5 : 0,
},
{
backgroundColor: isPressed && variant === 'tertiary' ?
'red' :
StyleSheet.flatten(styles[variant]).backgroundColor
},
style,
]
}
如本例所示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.