Browse Source

Video 7: Add a Remove Item Button to Each Row with React Native TouchableOpacity.

Frederic G. MARAND 7 years ago
parent
commit
c4ad32b1f4
2 changed files with 16 additions and 0 deletions
  1. 7 0
      app.js
  2. 9 0
      row.js

+ 7 - 0
app.js

@@ -46,6 +46,7 @@ class App extends Component {
       value: ""
     };
     this.handleAddItem = this.handleAddItem.bind(this);
+    this.handleRemoveItem = this.handleRemoveItem.bind(this);
     this.handleToggleAllComplete = this.handleToggleAllComplete.bind(this);
     this.handleToggleComplete = this.handleToggleComplete.bind(this);
     this.setSource = this.setSource.bind(this);
@@ -66,6 +67,11 @@ class App extends Component {
     this.setSource(newItems, newItems, { value: "" });
   }
 
+  handleRemoveItem(key) {
+    const newItems = this.state.items.filter((item) => item.key !== key);
+    this.setSource(newItems, newItems);
+  }
+
   handleToggleAllComplete() {
     const complete = !this.state.allComplete;
     const newItems = this.state.items.map((item) => ({
@@ -110,6 +116,7 @@ class App extends Component {
                 <Row
                   key={key}
                   onComplete={(complete) => this.handleToggleComplete(key, complete)}
+                  onRemove={() => this.handleRemoveItem(key)}
                   { ...value }
                 />
               );

+ 9 - 0
row.js

@@ -3,6 +3,7 @@ import {
   StyleSheet,
   Switch,
   Text,
+  TouchableOpacity,
   View
 } from "react-native";
 
@@ -16,6 +17,10 @@ const styles = StyleSheet.create({
     justifyContent: "space-between",
     padding: 10
   },
+  destroy: {
+    color: "#cc9a9a",
+    fontSize: 20
+  },
   text: {
     color: "#4d4d4d",
     fontSize: 24
@@ -39,6 +44,9 @@ class Row extends Component {
         <View style={styles.textWrap}>
           <Text style={[styles.text, complete && styles.complete]}>{this.props.text}</Text>
         </View>
+        <TouchableOpacity onPress={this.props.onRemove}>
+          <Text style={styles.destroy}>X</Text>
+        </TouchableOpacity>
       </View>
     );
   }
@@ -47,6 +55,7 @@ class Row extends Component {
 Row.propTypes = {
   complete: React.PropTypes.bool,
   onComplete: React.PropTypes.func,
+  onRemove: React.PropTypes.func,
   text: React.PropTypes.string
 };