Tengo un elemento PrimaryButton que tiene 3 variantes: primaria, secundaria y terciaria. Como puede ver en el estilo del componente Pressable, configuré el estilo predeterminado en función de la variante como esta styles[variant] . Ahora también quiero hacer que el color de fondo de ese componente presionable se vuelva rojo mientras se presiona si la variante del botón es terciaria. Ya tengo acceso al booleano isPressed que me dice si Pressable está presionado, sin embargo, no pude encontrar la manera de cambiar el color de fondo a rojo solo si la variante es terciaria.
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', }, });Mira si lo siguiente te ayuda. Si no, por favor dígame qué salió mal.
style = {({ pressed: isPressed }) => [ styles.button, styles[variant], { width, elevation: isPressed ? 5 : 0, ...(variant === 'tertiary') ? { backgroundColor: 'red' } : {} }, style, ]}revisa este paquete, muy útil para estas cosas. Ya no se recomiendan los estilos directamente en el nivel de campo. https://www.npmjs.com/package/isomorphic-style-loader Buena suerte
Para sobrescribir un estilo de un componente, en este caso, para cambiar el color de fondo a rojo solo si la variante es terciaria, puede usar el operador ternario.
Puede ser útil acceder a los estilos definidos para recuperar los colores de fondo de los otros botones. Para hacer eso, puede usar StyleSheet.flatten para no anular el estilo de color anterior aplicado.
style = { ({ pressed: isPressed }) => [ styles.button, styles[variant], { width, elevation: isPressed ? 5 : 0, }, { backgroundColor: isPressed && variant === 'tertiary' ? 'red' : StyleSheet.flatten(styles[variant]).backgroundColor }, style, ] }Como se ve en este ejemplo .