【问题标题】:React: Can't add a new task to my tasks's arrayReact:无法向我的任务数组添加新任务
【发布时间】:2023-01-11 02:04:51
【问题描述】:

我是 React 的新手,我正在尝试创建一个待办事项列表项目。 我正在尝试通过输入将新任务添加到我的任务数组中,但是当我按 Enter 时,屏幕上没有添加任何内容。有人可以帮忙吗?

应用程序.js

import React, { Component } from "react";
import Tasks from "./Components/tasks";

class App extends Component {

    constructor(props) {
      super(props);

      this.state = {
          newTask: '',
          tasks: [
              { id: 1, text: "study" },
              { id: 2, text: "read" },
              { id: 3, text: "gym" },
          ]
      };
    }

    handleSubmit(e) {
      e.preventDefault();
      const tasks = [...this.state.tasks];
      tasks.push({id: 4, text: this.state.newTask});
      this.setState({ tasks: tasks });
    }

    handleChange= (e) => {
      this.setState({newTask: e.target.value});
    }

    render() {
        return (
            <div className="App">
                <h1>To Do List</h1>

                <form onSubmit={this.handleSubmit}>
                  <input type="text" placeholder="Enter task" value={this.state.newTask} onChange={this.handleChange}/>
                </form>

                <Tasks tasks={this.state.tasks} />
            </div>
        );
    }
}

export default App;

另外我在控制台上收到此错误: error

【问题讨论】:

  • handleSubmit(以及一般的事件处理程序)需要在 ctor 和 bind 中绑定到组件实例,或者通过使其成为箭头函数。

标签: javascript html reactjs


【解决方案1】:

你需要将你的函数绑定到类

简单的解决方案是使用箭头函数语法

   handleSubmit = (e) =>  {

代替

handleSubmit(e) {

还有其他方法可以做到这一点..

您可以阅读本文以了解更多https://www.freecodecamp.org/news/this-is-why-we-need-to-bind-event-handlers-in-class-components-in-react-f7ea1a6f93eb/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-12
    • 2018-03-02
    • 2015-02-23
    • 1970-01-01
    • 2020-01-21
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多