美文网首页由浅入深的学习React全家桶
【ReactNative】入门:从todo App开始(4)

【ReactNative】入门:从todo App开始(4)

作者: LesliePeng | 来源:发表于2017-03-31 13:36 被阅读106次

1. 给每一个todo item项添加switch

这个switch用来标记已完成或者未完成。

Screen Shot 2017-03-31 at 1.33.33 PM.png

新建一个row.js文件如下
row.js

import { View, Text, StyleSheet, Switch } from 'react-native';
...省略
return (
      <View style={styles.container}>
        <Switch
          value={complete}
         
        />
...

现在添加一个todo item会看到左边出现了一个switch,默认值是false。

下面希望当item的complete变成true的时候会变成被划掉的样式:
先新写一个style

complete: {
    textDecorationLine: "line-through"
  },

然后

render() {
    const { complete } = this.props;
    return (
      <View style={styles.container}>
        <Switch
          value={complete}
          onValueChange={this.props.onComplete}
        />
        <View style={styles.textWrap}>
          <Text style={[styles.text, complete && styles.complete]}>{this.props.text}</Text>
        </View>
      </View>
    );
  }

特别注意此处的语法

<Text style={[styles.text, complete && styles.complete]}>{this.props.text}</Text>

将两个style样式写在一个数组里,就是当第二个判断为true的时候,数组后面的项会生效,如其中有相同的内容优先级高于前面的项。

现在如果使用toggleAll的那个对勾按钮可以看到效果

很明显现在需要加上能够单独toggle每一项的function

<Switch
value={complete}
onValueChange={this.props.onComplete}
/>

回到App.js中补上这个方法

handleToggleComplete(key, complete) {
    const newItems = this.state.items.map((item) => {
      if (item.key !== key) return item;
      return {
        ...item,
        complete
      }
    })
    this.setSource(newItems, newItems);
  }
return (
                <Row
                  key={key}
                  onComplete={(complete) => this.handleToggleComplete(key, complete)}
                  {...value}
                />
              )

现在已经能够通过switch来toggle每一项了。

相关文章

网友评论

    本文标题:【ReactNative】入门:从todo App开始(4)

    本文链接:https://www.haomeiwen.com/subject/ovfvottx.html