如何在 reactjs 中将函数和按钮绑定在一起

How do I bind the function and button together in reactjs

我制作了一个按钮,当它被点击时应该保存 post。它在被点击时调用一个函数,但我认为它没有正确传递状态,或者绑定可能没有正常工作,我不知道哪里出了问题。我希望有人能纠正我。

当前显示的错误是:

第 12 行:'title' 未定义 no-undef

第 12 行:'description' 未定义 no-undef

第 12 行:'id' 未定义 no-undef

import React, { Component } from "react";
import { Link } from "react-router-dom";
import { Button } from "react-bootstrap";


const savepost = async () => {
  const post = { ...title, ...description, ...id };
  const request = {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    }
  };
  if (post.id == null) delete post.id;
  try {
    const response = await fetch("/api/updateposts", {
      ...request,
      body: JSON.stringify(this.state)
    });
    const data = await response.json();
    if (data.status == 200) {
      console.log("success", "post saved successfully!");
    } else {
      console.log(
        "danger",
        "An error has occured while updating the post. Please try again"
      );
    }
  } catch (ex) {
    console.error(ex.stack);
    console.log(
      "danger",
      "An error has occured while updating the post. Please try again"
    );
  }
};


export default class MainText extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: "",
      description: "",
      id: ""
    };
  }

  render() {
    return (
      <>
              <Link to="/about">
                <Button className="btn savebtn" onClick={savepost}>
                  Save <i className="fas fa-save" />
              </Link>
      </>

好的,您没有向函数传递任何参数 首先将参数传递为

return (
  <>
          <Link to="/about">
            <Button className="btn savebtn" 
             onClick={() => savepost({ ...this.state})}>
              Save <i className="fas fa-save" />
          </Link>
  </>
  )

然后在你的函数中将这些作为

const savepost = async ({ title, description, id}) => {
  const post = { title, description,id };
  ... // remaining code 
}

希望对您有所帮助

您必须将状态传递给函数,因为您的函数无法访问它,除非您像这样传递它:

<Link to="/about">
  <Button className="btn savebtn" onClick={() => savepost(this.state)}>
    Save <i className="fas fa-save" />
  </Button>
</Link>


const savepost = async (props) => {
   const post = { props.title, props.description, props.id };
}

我已经对此进行了 StackBlitz,但首先是您没有将任何参数传递给 savepost 函数(当它需要 3 - 标题、描述和 ID ).希望这对您有所帮助,问候。