gpt4 book ai didi

javascript - 如何在 reactjs 中将函数和按钮绑定(bind)在一起

转载 作者:行者123 更新时间:2023-11-29 15:07:43 25 4
gpt4 key购买 nike

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

当前显示的错误是:

第 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
}

希望对你有帮助

关于javascript - 如何在 reactjs 中将函数和按钮绑定(bind)在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58264362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com