Skip to content

Instantly share code, notes, and snippets.

@chuyihuang
Created August 29, 2017 10:14
Show Gist options
  • Save chuyihuang/d5ad405a81c1d696294d33c3445c00dc to your computer and use it in GitHub Desktop.
Save chuyihuang/d5ad405a81c1d696294d33c3445c00dc to your computer and use it in GitHub Desktop.
week_3_demo_9
import React, { Component } from 'react';
import { View, TextInput, Text, Button } from 'react-native';
import store from '../store';
import * as Types from '../types';
import {connect} from 'react-redux';
const mapStateToProps = (state) => {
return {
todos: state.todos,
}
}
class Todo extends Component {
constructor(props) {
super(props);
this.state = {
value: null,
todos: this.props.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>
);
}
}
export default connect(mapStateToProps)(Todo);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment