[英]How to add two functions to one onClick
I have two functions that need to be hung on one button.我有两个功能需要挂在一个按钮上。 One function writes data to the Firestore, and the other writes a picture to Storage.
一个 function 将数据写入 Firestore,另一个将图片写入 Storage。 How can I add them to the onClick on a single button?
如何通过一个按钮将它们添加到 onClick?
const Header = () => { const submitHandler = async (e) => { e.preventDefault(); try { await setDoc(doc(housesRef, enteredTitle), { title: enteredTitle, descr: enteredText, lat: enteredLatitude, lon: enteredLongitude, }); togglePopup(); setEnteredTitle(""); setEnteredText(""); setEnteredLatitude(""); setEnteredLongitude(""); } catch (err) { alert(err); } }; const imageUpload = () => { const imageRef = ref(storage, `image/${uploadImage.name}`); uploadBytes(imageRef, uploadImage).then(() => { alert("Image Uploaded"); }); }; return ( <div className="header">... <input type="submit" value="Add" onClick={} />... ); };
Simply create a new function that calls those two different functions,只需创建一个调用这两个不同函数的新 function,
like so,像这样,
const myEncapsulatingFunc = (func1_params, func2_params) => {
myFunc1(func1_params);
myFunc2(func2_params);
}
Attach myEncapsulatingFunc
to the onclick event and pass in the relevant parameters.将
myEncapsulatingFunc
附加到 onclick 事件并传入相关参数。
The simple answer is you can't简单的答案是你不能
You can however, just call them seperately like this:但是,您可以像这样单独调用它们:
return (
<div className="header">
...
<input
type="submit"
value="Add"
onClick={() => {
func1();
func2()
} }
/>
...
);
Why not calling imageUpload inside onSubmitHandler and just passing onSubmitHandler to the onClick?为什么不在 onSubmitHandler 内部调用 imageUpload 并将 onSubmitHandler 传递给 onClick?
const submitHandler = async (e) => {
e.preventDefault();
imageUpload()
try {
...
} catch (err) {
alert(err);
}
};
<input
type="submit"
value="Add"
onClick={onSubmitHandler}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.