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每一項了。