1. 給每一個(gè)todo item項(xiàng)添加switch
這個(gè)switch用來標(biāo)記已完成或者未完成胳施。
Screen Shot 2017-03-31 at 1.33.33 PM.png
新建一個(gè)row.js
文件如下
row.js
import { View, Text, StyleSheet, Switch } from 'react-native';
...省略
return (
<View style={styles.container}>
<Switch
value={complete}
/>
...
現(xiàn)在添加一個(gè)todo item會(huì)看到左邊出現(xiàn)了一個(gè)switch闸餐,默認(rèn)值是false惭适。
下面希望當(dāng)item的complete變成true的時(shí)候會(huì)變成被劃掉的樣式:
先新寫一個(gè)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>
將兩個(gè)style樣式寫在一個(gè)數(shù)組里薪铜,就是當(dāng)?shù)诙€(gè)判斷為true的時(shí)候含衔,數(shù)組后面的項(xiàng)會(huì)生效股耽,如其中有相同的內(nèi)容優(yōu)先級(jí)高于前面的項(xiàng)颜曾。
現(xiàn)在如果使用toggleAll的那個(gè)對(duì)勾按鈕可以看到效果
很明顯現(xiàn)在需要加上能夠單獨(dú)toggle每一項(xiàng)的function
<Switch
value={complete}
onValueChange={this.props.onComplete}
/>
回到App.js
中補(bǔ)上這個(gè)方法
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}
/>
)
現(xiàn)在已經(jīng)能夠通過switch來toggle每一項(xiàng)了泽示。