javascript - 如何为我的函数访问数组中的属性?

标签 javascript reactjs

我在 React 中制作了一个待办事项列表。我已经设置了一些属性以在添加待办事项时提取。 (文本、键和编辑模式)。

我试图将其设置为当我双击待办事项元素时,我双击的特定元素进入编辑模式。为此,我设置了一个函数,当一个

  • 元素的 editMode 属性设置为 true 时,它​​将变成一个要编辑的文本框。

    但是,当我设置它时,它会将所有

  • 元素(待办事项)转换为编辑模式,我无法弄清楚如何具体选择我单击进入的元素编辑模式。

    我如何使用我的代码实现这一目标?

    import React from "react";
    import { isTemplateElement, tsStringKeyword } from "@babel/types";
    
    class TodoListt extends React.Component {
      state = {
        userInput: '',
        todos: [],
        editMode: false
      }
    
      handleChange(e, index) {
        this.setState({
          userInput: (e)
        })
        console.log(this.state.userInput)
      }
    
    
      handleSubmit(e, index) {
        e.preventDefault();
        const { todos, userInput } = this.state;
        this.setState({
          todos: [...todos, {
            text: userInput,
            key: Date.now(),
            editMode: false
    
          }],
          userInput: ''
        }
        )
      }
    
      handleDelete(index) {
        const todos = [...this.state.todos];
        todos.splice(index, 1);
        this.setState({
          todos
        })
      }
    
      handleEdit(index) {
        const todos = [...this.state.todos];
        console.log(todos.text)
      }
    
      render() {
        return (
    
          < div >
            <form onSubmit={(e) => this.handleSubmit(e)}>
              <input
                type="text"
                class="form-control mb-2"
                placeholder="enter a todo..."
                onChange={(e) => this.handleChange(e.target.value)}
                value={this.state.userInput}
              />
              <button type="submit" class="btn btn-primary">Submit</button>
            </form>
    
            <ul class="list-group">
    
              {this.state.todos.map((todos, index) => (
    
                this.state.editMode[index] ?
                  <div>
                    <input type="text" defaultValue={todos.text} />
                  </div>
                  :
    
    
                  <li
                    key={todos.key}
                    class="list-group-item"
                    onDoubleClick={(index) => this.handleEdit(index)}>
                    {todos.text}
                    <div class="delButton">
                      <button class="btn btn-danger" onClick={(index) => this.handleDelete(index)}>Remove</button>
                    </div>
                  </li>
              )
              )
              }
    
            </ul>
          </div>
        )
      }
    }
    export default TodoListt;
    
  • 最佳答案

    你真的很接近!我为您创建了一个沙箱:https://codesandbox.io/s/practical-cache-52k52

    为了利用 todos 对象,我们将使用 map 函数创建正在编辑的 todo 的新实例。

    import React from "react";
    import { isTemplateElement, tsStringKeyword } from "@babel/types";
    
    class TodoListt extends React.Component {
      state = {
        userInput: "",
        todos: [],
        editMode: false
      };
    
      handleChange(e, index) {
        this.setState({
          userInput: e
        });
      }
    
      handleSubmit(e, index) {
        e.preventDefault();
        const { todos, userInput } = this.state;
        this.setState(
          {
            todos: [
              ...todos,
              {
                text: userInput,
                key: Date.now(),
                editMode: false
              }
            ],
            userInput: ""
          },
          () => console.log(this.state)
        );
      }
    
      handleDelete(index) {
        const todos = [...this.state.todos];
        todos.splice(index, 1);
        this.setState({
          todos
        });
      }
    
      handleEdit(index) {
        const todos = [...this.state.todos];
        const updatedTodos = todos.map((todo, todoIndex) => {
          if (index == todoIndex) {
            return {
              ...todo,
              editMode: true
            };
          } else {
            return todo;
          }
        });
        this.setState(
          {
            ...this.state,
            todos: updatedTodos
          },
          () => console.log(this.state)
        );
      }
    
      handleUpdateChange = (e, index) => {
        const todos = [...this.state.todos];
        const updatedTodos = todos.map((todo, todoIndex) => {
          if (index == todoIndex) {
            return {
              ...todo,
              text: e.target.value
            };
          } else {
            return todo;
          }
        });
        this.setState({
          ...this.state,
          todos: updatedTodos
        });
      };
    
      handleUpdateSubmit(e, index) {
        e.preventDefault();
        const todos = [...this.state.todos];
        const updatedTodos = todos.map((todo, todoIndex) => {
          if (index == todoIndex) {
            return {
              ...todo,
              editMode: false
            };
          } else {
            return todo;
          }
        });
        this.setState(
          {
            ...this.state,
            todos: updatedTodos
          },
          () => console.log(this.state)
        );
      }
    
      render() {
        return (
          <div>
            <form onSubmit={e => this.handleSubmit(e)}>
              <input
                type="text"
                class="form-control mb-2"
                placeholder="enter a todo..."
                onChange={e => this.handleChange(e.target.value)}
                value={this.state.userInput}
              />
              <button type="submit" class="btn btn-primary">
                Submit
              </button>
            </form>
    
            <ul class="list-group">
              {this.state.todos.map((todos, index) =>
                this.state.editMode[index] ? (
                  <div>
                    <input type="text" value={todos.text} />
                  </div>
                ) : todos.editMode ? (
                  <form onSubmit={e => this.handleUpdateSubmit(e, index)}>
                    <input
                      value={todos.text}
                      onChange={e => this.handleUpdateChange(e, index)}
                    />
                  </form>
                ) : (
                  <li
                    key={todos.key}
                    class="list-group-item"
                    onDoubleClick={() => this.handleEdit(index)}
                  >
                    {todos.text}
                    <div class="delButton">
                      <button
                        class="btn btn-danger"
                        onClick={index => this.handleDelete(index)}
                      >
                        Remove
                      </button>
                    </div>
                  </li>
                )
              )}
            </ul>
          </div>
        );
      }
    }
    export default TodoListt;
    

    关于javascript - 如何为我的函数访问数组中的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56211701/

    相关文章:

    带有三重 => 的 Javascript 函数语法

    javascript - 检查数组元素的第一个字符

    javascript - 在 Ember.js 上使用 bower install 安装 dygraphs 失败

    javascript - 异常 : Cannot read property 'addInstrumentToStage' of undefined

    javascript - 如果数据更改,则使按钮处于事件状态

    javascript - 如何使用django + react有效处理大文件上传?

    javascript - 即使所选选项没有更改,是否有任何方法可以在 Chrome 中的 SELECT 元素上触发点击事件?

    javascript - ReactJs - 语法错误 : embedded: Unterminated JSX contents

    reactjs - React Redux : Use data from props or get data directly from redux-store? 哪一个更好?

    reactjs - React SignalR - 不要在 URL 中发送承载 token