javascript - 如何从状态中获取数据并编辑表单中的元素?

标签 javascript reactjs ecmascript-6

我想得到如下效果:点击按钮->调用函数toggle->将被点击项的索引保存在状态this.state.index中->显示编辑表单--->获取被点击项的数据元素到表单 -> 编辑数据 -> 保存

当尝试调用切换函数并在某个状态下写入index 时,索引不会保存。将索引保存在状态后,我想使用它并访问 todo = this.state.todos [this.props.index] 中的点击元素。我在 form 属性中发送被点击的 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;

最佳答案

让每个待办事项管理它的状态,在编辑时它将显示该待办事项的表单。

class Todo extends Component {

  state = {
    isEditing: false,
    startDate: new Date(),
    description: '',
  }

  setEditing = () => {
    this.setState({
      isEditing: !this.state.isEditing
    })
  }

  handleChange = (date) => {
    this.setState({
      startDate: date
    });
  }

  handleDescription = (evt) => {
    this.setState({
      description: evt.target.value
    })
  }

  formatDate = () => {
    const d = this.state.startDate;

    return d.getFullYear().toString().substring(2) + "-" +
      ("00" + (d.getMonth() + 1)).slice(-2) + "-" +
      ("00" + d.getDate()).slice(-2) + ", " +
      ("00" + d.getHours()).slice(-2) + ":" +
      ("00" + d.getMinutes()).slice(-2)
  }

  onSave = () => {

    const { description } = this.state;

    this.props.update(this.props.index, { description, date: this.formatDate() });

    this.setState({
      isEditing: false
    })
  }

  componentDidMount = () => {
    const { todo } = this.props;

    this.setState({
      description: todo.description,
      startDate: new Date(todo.date)
    })
  }

  render() {

    return (
      <div>
        {this.state.isEditing

          ? (<EditForm
            handleChange={this.handleChange}
            description={this.state.description}
            startDate={this.state.startDate}
            handleDescription={this.handleDescription}
            onSave={this.onSave}
          />)
          : (
            <li>
              <div>
                {this.props.todo.date}
              </div>
              <div>
                {this.props.todo.description}
              </div>
              <button onClick={() => this.setEditing()}>Edit</button>
            </li>
          )

        }
      </div>
    )
  }
}

编辑表单

class EditForm extends Component {
  render() {
    return (
      <div>
        <DatePicker
          selected={this.props.startDate}
          onChange={this.props.handleChange}
          showTimeSelect
          timeFormat="HH:mm"
          value={this.props.startDate}
          dateFormat="yy-MM-dd, hh:mm"
          timeCaption="time"
        />
        <textarea onChange={(e) => this.props.handleDescription(e)} value={this.props.description}></textarea>
        <button onClick={this.props.onSave} type="submit">Save</button>
      </div>
    )
  }
}

Demo

关于javascript - 如何从状态中获取数据并编辑表单中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56509312/

相关文章:

javascript - 删除 CKEditor 4 中的注释

php - 如何将 javascript 变量传递给 php 并重新加载框架

reactjs - 获取断点以使用 jest、Visual Studio 代码和自定义 typescript 转换器

reactjs - 为什么 useState 导致 dom 渲染两次

reactjs - 如何将 firestoreConnect 指向 React-Redux-Firebase 中的嵌套集合?

javascript - 将单个 getServerSideProps 方法导入 Nextjs 中的多个页面

javascript - 按即将到来的日期对日期为字符串的数组进行排序

javascript - Select2 AJAX 不起作用

javascript - Angular Date 管道,以及一个带有 Momentjs 的简单计时器

javascript - 如何在另一个 mixins 函数中使用 mixins 函数?