Skip to content

Instantly share code, notes, and snippets.

@chuyihuang
Created August 29, 2017 09:45
Show Gist options
  • Save chuyihuang/638644c9ad93b05659cc72ece4af6614 to your computer and use it in GitHub Desktop.
Save chuyihuang/638644c9ad93b05659cc72ece4af6614 to your computer and use it in GitHub Desktop.
week_3_demo_5
import React, { Component } from 'react';
import { View, TextInput, Text, Button } from 'react-native';
import store from './app/store';
import * as Types from './app/types';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
value: null,
todos: store.getState().todos,
}
}
createTodo = () => {
let {todos} = this.state;
store.dispatch({
type: Types.ADD_TODO,
payload: {
id: todos.length + 1,
content: this.state.value,
checked: false,
}
});
console.log(store.getState());
this.setState({
value: null,
});
}
handleToggle = (toggleTodo) => {
let filteredTodos = this.state.todos.filter((todo) => todo.id !== toggleTodo.id);
this.setState({
todos: [...filteredTodos, {...toggleTodo, checked: !toggleTodo.checked}].sort((a,b) => a.id > b.id)
})
}
showTodoList = () => {
return this.state.todos.map((todo, index) => {
return (
<View key={`todo_${index}`} style={{flexDirection: 'row', padding: 10,}}>
<Button title="完成" onPress={() => this.handleToggle(todo)} />
<Text style={{textDecorationLine: (todo.checked ? 'line-through' : 'none')}}>{todo.content}</Text>
</View>
);
})
}
render() {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<TextInput
style={{width: '80%', borderBottomWidth: 1, borderBottomColor: '#aaaaaa'}}
placeholder="輸入待做事項..."
value={this.state.value}
onChangeText={(value) => this.setState({value})}
/>
<Button title="送出" onPress={() => this.createTodo()} color="#c40000" />
{/* todo list */}
<View style={{width: '100%', borderTopWidth: 2}}>
{this.showTodoList()}
</View>
</View>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment