reactjs——如何将作为道具传递的函数更改为React组件?
发布时间:2022-05-01 22:43:21 318
相关标签: # node.js
我正在尝试用撤销操作构建一个可重用的SnackBar(显示刚刚发生的事情信息的小弹出窗口)组件。我想这样使用它:
主要成分
import SnackBar from "./SnackBar";
import { useState } from "react";
const MainComponent({item}) => {
const [snackBarVisible, setSnackBarVisible] = useState(false);
const [snackBarMessage, setSnackBarMessage] = useState("");
const [undoFunction , setUndoFunction ] = useState(null);
//var undoFunction = null;
const undoAddToFav = () => {
//code that removes from favorites the stuff that was just added
console.log("removed last added product from favs");
};
const undoAddToCart = () => {
//code that removes from cart the last added product
console.log("removed last added product from cart");
}
const addToCart = (item) => {
//some code
setSnackBarMessage("Item added to cart");
//HELP NEEDED HERE
//undoFunction = undoAddToCart; // this doesn't work at all (no error messages)
setUndoFunction(() => undoAddToCart()) // this executes undoAddToCart when addToCart is called and not on button press
setSnackBarVisible(true);
}
const addToFavorites = (item) => {
//some code
setSnackBarMessage("Item added to favourites");
//undoFunction = undoAddToFav ; // <== HELP NEEDED HERE
//setUndoFunction(() => undoAddToCart())
setSnackBarVisible(true);
}
const displaySnackBar = () => {
setSnackBarMessage("Some info");
setSnackBarVisible(true);
//this one has no "undo" button
}
//some other stuff
return (
//some other stuff that calls the actions above
);
};
子组件
我希望此操作是可选的。
export default const SnackBar = ({snackBarMessage, snackBarVisible, undoFunction}) => {
//some stuff
return (
<>
//some stuff - handle visibility, etc
//help needed here as well - how do I display the button only when the function prop is passed?
{undoFunction && }; //this doesn't work properly
{snackBarMessage}
;
</>
);
};
我试过用useState、useCallback、useMemo和useRef来处理这个问题,但似乎没有任何效果。
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报