您的位置:首页 > 编程语言

RN TODO代码解析之二

2017-12-08 15:42 309 查看
在第二篇里我们用flatlist改写之前的版本,并且使用es6的箭头函数实现列表项的渲染。
import React, {
Component,
PropTypes
} from 'react'

import {
AppRegistry,
StyleSheet,
View,
Text,
Image,
Button,
TextInput,
ListView,
Switch,
TouchableOpacity,
FlatList
} from 'react-native'

class TodoApp extends Component {

constructor(props) {
super(props);

// Set the initial state.
this.state = {
onlyShowNotDone: false,
todos: [
this.makeTodo(3),
this.makeTodo(2, true),
this.makeTodo(1)
],
}
}

addTodo() {
// Inject a new todo at the start of the list.
this.setState({
todos: [this.makeTodo(), ...this.state.todos]
});
}

makeTodo(number, done) {
const id = number ? number : this.state.todos.length + 1;
return {
id: id,
done: done ? true : false,
text: 'Todo Item #' + id,
key: id
}
}

toggleTodo(todo) {
let newTodo = { ...todo };
newTodo.done = !todo.done;
const index = this.state.todos.indexOf(todo);
// Recreate a list but replace the existing one.
let todos = [...this.state.todos.slice(0, index), newTodo, ...this.state.todos.slice(index + 1)];
this.setState({
todos: todos
});
}

render() {
const todos = this.state.todos.filter((todo) => {
if (this.state.onlyShowNotDone) {
return !todo.done;
}
return true;
});
return (
<View style={styles.container}>
<View style={styles.options}>
<TouchableOpacity onPress={() => this.addTodo()} style={styles.add}>
<Text>+ Add a todo</Text>
</TouchableOpacity>
<View style={styles.hide}>
<Text>Hide done</Text>
<Switch
onValueChange={(value) => this.setState({ onlyShowNotDone: value })}
value={this.state.onlyShowNotDone} />
</View>
</View>

<FlatList
data={todos}
renderItem={
({ item, index }) => (
<View style={styles.todo} key={item.id}>
<View>
<Switch onValueChange={() => this.toggleTodo(item)} value={item.done} />
</View>
<View>
<Text>{item.text}</Text>
</View>
</View>
)}
/>
</View>
);
}
}

const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
add: {
flex: 1,
padding: 10
},
hide: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-around'
},
options: {
flexDirection: 'row',
marginTop: 50,
marginBottom: 30
},
todo: {
flex: 1,
flexDirection: 'row',
marginBottom: 10
}
});

export default class App extends React.Component {
render() {
return <TodoApp />;
}
}


Todo demo系列之第二版,改动点:
a.列表改成了flatlist, 直接使用数据源todos就可以了,无需自己创建和填充专门的datasource,这种使用方式非常接近原生的tableview。
需要注意的是: 1.绑定的renderItem方法的参数名必须是item, index, 这里的item不能换成其他字符串! 2.todos里面的项需要有一个key(可以和id相同),否则会告警。

b.将renderItem方法直接使用箭头函数来实现了,移除了此前单独的渲染方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: