Browse Source

Video 6: Add a Complete Toggle with React Native Switch.

Frederic G. MARAND 7 years ago
parent
commit
b32141ce5a
2 changed files with 37 additions and 1 deletions
  1. 15 0
      app.js
  2. 22 1
      row.js

+ 15 - 0
app.js

@@ -47,6 +47,7 @@ class App extends Component {
     };
     this.handleAddItem = this.handleAddItem.bind(this);
     this.handleToggleAllComplete = this.handleToggleAllComplete.bind(this);
+    this.handleToggleComplete = this.handleToggleComplete.bind(this);
     this.setSource = this.setSource.bind(this);
   }
 
@@ -75,6 +76,19 @@ class App extends Component {
     this.setSource(newItems, newItems, { allComplete: complete });
   }
 
+  handleToggleComplete(key, complete) {
+    const newItems = this.state.items.map((item) => {
+      if (item.key !== key) {
+        return item;
+      }
+      return {
+        ...item,
+        complete
+      };
+    });
+    this.setSource(newItems, newItems);
+  }
+
   render() {
     // console.log("App state", this.state);
     return (
@@ -95,6 +109,7 @@ class App extends Component {
               return (
                 <Row
                   key={key}
+                  onComplete={(complete) => this.handleToggleComplete(key, complete)}
                   { ...value }
                 />
               );

+ 22 - 1
row.js

@@ -1,11 +1,15 @@
 import React, { Component } from "react";
 import {
   StyleSheet,
+  Switch,
   Text,
   View
 } from "react-native";
 
 const styles = StyleSheet.create({
+  complete: {
+    textDecorationLine: "line-through"
+  },
   container: {
     alignItems: "flex-start",
     flexDirection: "row",
@@ -15,18 +19,35 @@ const styles = StyleSheet.create({
   text: {
     color: "#4d4d4d",
     fontSize: 24
+  },
+  textWrap: {
+    flex: 1,
+    marginHorizontal: 10
   }
 });
 
 class Row extends Component {
   render() {
     // console.log("Row.render", this.props);
+    const { complete } = this.props;
     return (
       <View style={styles.container}>
-        <Text style={styles.text}>{this.props.text}</Text>
+        <Switch
+          value={complete}
+          onValueChange={this.props.onComplete}
+        />
+        <View style={styles.textWrap}>
+          <Text style={[styles.text, complete && styles.complete]}>{this.props.text}</Text>
+        </View>
       </View>
     );
   }
 }
 
+Row.propTypes = {
+  complete: React.PropTypes.bool,
+  onComplete: React.PropTypes.func,
+  text: React.PropTypes.string
+};
+
 export default Row;