我想得到如下效果:点击按钮->调用函数切换->状态this.state.index保存点击项的索引->显示编辑表单--->获取点击元素的数据到表单-> 编辑数据-> 保存
尝试调用切换函数并index在状态中写入时,索引不会保存。将索引保存在状态后,我想使用它并可以访问todo = this.state.todos [this.props.index]. 我todo在表单属性中发送点击的数据。在表格中,他通过 引用了这个value = this.props.todo.date。我正在使用date-picker-react图书馆。有人可以指导我吗?
应用程序
class App extends Component {
constructor() {
super();
this.state = {
todos: [],
index: null,
editing: false
};
}
update = (propertyName) => (event) => {
const { todo } = this.state;
const newTodo = {
...todo,
[propertyName]: event.target.value
};
this.setState({ todo: newTodo });
}
toggle = (index) => {
this.setState({
editing: !this.state.editing,
index: index
})
}
createTodo = (todo) => {
const new = this.state.todos.slice();
new.push(todo);
this.setState({todos: new});
}
render () {
return (
<ul>
{
this.state.todos
.map(index => {
<Todo
key= {index}
index = {this.state.index}
toggle = {this.toggle}
todo={this.state.todos[index]}
editing = {this.state.editing}
update = {this.update}
/>
})
}
</ul>
);
}
}
export default App;
待办事项/待办事项
class Todo extends Component {
render() {
if (this.props.isEditing) {
return (
<EditForm
todo = {this.props.todos[this.props.index]}
update = {this.props.update}
/>
)
}
return (
<li>
<div>
{this.props.todo.date}
</div>
<div>
{this.props.todo.description}
</div>
<button onClick={() => this.props.toggle(index)}></button>
</li>
)
}
}
export default Todo;
编辑表格/编辑表格
class EditForm extends Component {
constructor(){
super();
this.state = {
startDate: new Date()
}
}
todo(e) {
event.preventDefault();
const todo = {
date: this.state.startDate,
description: this.desc.value
}
this.props.addTodo(todo);
}
handleChange = (date) => {
this.setState({
startDate: date
});
}
render() {
return (
<form onSubmit={(e) => this.todo(e)}>
<DatePicker
selected={this.state.startDate}
onChange={this.update('date')} value=
{this.state.todo.date}
showTimeSelect
timeFormat="HH:mm"
value={todo.date}
dateFormat="yy-MM-dd, hh:mm"
timeCaption="time"
/>
<textarea ref={(input) => this.description = input} value=
{todo.description} onChange={this.update('description')}
value={this.state.todo.description}></textarea>
<button type="submit">Save</button>
</form>
)
}
}
export default EditForm;