Issue
I'm currently working on an app prototype with react native. There's a lot out there on how to change the color of a component, here Touchable or Pressable, when pressing it (=> onPress). But how do i change the backgroundcolor of such a component permanently after clicking – with onPressOut?. Example:
simple "Click me" component that has a green background by default. If clicked once, it should change to a red background. Clicked once again, it should go back to green (and so on).
Can you help me with this?
Solution
You need to control it using the state
of component.
I did a live demo for you:
https://codesandbox.io/s/silent-sea-5331l?file=/src/App.js
import React, { useState } from "react";
import { View, TouchableOpacity } from "react-native";
const App = props => {
const [selected, setSelected] = useState(false);
return (
<View style={{ width: "30%", alignItems: "center", marginTop: 20 }}>
<TouchableOpacity
onPress={() => setSelected(!selected)}
style={{ backgroundColor: selected ? "red" : "transparent" }}
>
Press me
</TouchableOpacity>
</View>
);
};
export default App;
Answered By - Deivison Sporteman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.