首页 > 解决方案 > 我想在 ReactJs 的 onClick 中有 2 种方法,但它不起作用

问题描述

我正在尝试同时调用 2 个方法,onClick其中是代码底部的按钮startEdit()。我确实在谷歌上搜索过,我写了他们告诉我要做的事情,但它不起作用,它告诉我一个错误!我是 ReactJs 的新手,我也在尝试将 reactjs 与 Django 一起使用。showModal()edit

这是我的代码

import React from "react";
import "bootstrap/dist/css/bootstrap.css";
import { Modal } from "antd";

class ListItem extends React.Component {
  // For Item list from API
  constructor(props) {
    super(props);

    this.state = {
      todoList: [],
      activeItem: {
        id: null,
        title: "",
        completed: false,
      },
      editing: false,
    };
    this.fetchTasks = this.fetchTasks.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.getCookie = this.getCookie.bind(this);
  }

  // function for csrf token just like django documentation told
  getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== "") {
      const cookies = document.cookie.split(";");
      for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i].trim();
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) === name + "=") {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }

  componentWillMount() {
    this.fetchTasks();
  }

  fetchTasks() {
    fetch("http://localhost:8000/api/task-list/")
      .then((response) => response.json())
      .then((data) =>
        this.setState({
          todoList: data,
        })
      );
  }

  handleChange(e) {
    let name = e.target.name;
    let value = e.target.value;
    console.log("Name:", name);
    console.log("Value:", value);

    this.setState({
      activeItem: {
        ...this.state.activeItem,
        title: value,
      },
    });
  }

  handleSubmit(e) {
    e.preventDefault();
    console.log("ITEM:", this.state.activeItem);
    // Apply the csrf token just like django documentation told
    let csrftoken = this.getCookie("csrftoken");
    let url = "http://localhost:8000/api/task-create/";
    fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-CSRFToken": csrftoken,
      },
      body: JSON.stringify(this.state.activeItem),
    })
      .then((response) => {
        this.fetchTasks();
        this.setState({
          activeItem: {
            id: null,
            title: "",
            completed: false,
          },
        });
      })
      .catch(function (error) {
        console.log("Error:", error);
      });
  }

  startEdit(task) {
    this.setState({
      activeItem: task,
      editing: true,
    });
  }

  // For Modal
  state = { visible: false };

  showModal = () => {
    this.setState({
      visible: true,
    });
  };

  handleCancel = (e) => {
    console.log(e);
    this.setState({
      visible: false,
    });
  };

  render() {
    let tasks = this.state.todoList;
    let self = this;

    return (
      <div className="container col-md-6">
        <div className="container mt-5">
          <div className="form-group">
            <button
              onClick={this.showModal}
              id="btn-create-task"
              className="btn mt-4 col-md-12"
            >
              Create Task
            </button>
          </div>
          {/* For Modal */}

          <Modal
            title="Task"
            visible={this.state.visible}
            onCancel={this.handleCancel}
            onOk={this.handleSubmit}
            centered
            footer={[
              <button
                key="Cancel"
                onClick={this.handleCancel}
                className="btn btn-outline-info"
              >
                Cancel
              </button>,
              <button
                id="submit"
                onClick={this.handleSubmit}
                key="Add"
                type="submit"
                className="btn btn-outline-primary"
              >
                Add
              </button>,
            ]}
          >
            <div className="form-group">
              <input
                onChange={this.handleChange}
                value={this.state.activeItem.title}
                className="form-control col-md-12"
                placeholder="Enter the task"
                type="text"
              />
            </div>
          </Modal>
        </div>
        <div id="task-container">
          <div id="list-wrapper">
            {tasks.map(function (task, index) {
              return (
                <div key={index} className="task-wrapper flex-wrapper">
                  <div id="item-list" className="float-left">
                    <span>{task.title}</span>
                  </div>
                  <div id="edit-delete-btn">
                    <button
                      onClick={() => {self.startEdit(task); this.showModal;}}
                      className="btn btn-outline-primary"
                    >
                      Edit
                    </button>
                    <button className="btn btn-outline-dark ml-2">Done</button>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    );
  }
}
export default ListItem;

这是我得到的错误 Line 186:61: Expected an assignment or function call and instead saw an expression no-unused-expressions

标签: javascriptreactjs

解决方案


错误:onClick={() => {self.startEdit(task); this.showModal;}} 正确:onClick={() => {self.startEdit(task); self.showModal();}}


推荐阅读