Sat*_*abh 7 reactjs typescript-typings next.js react-hooks
我想调用一个自定义挂钩,该挂钩将在单击按钮时发送电子邮件。
customHook.ts
async function sendEmail(userName: string, userEmail: string, userPhone: string) {
const mailToUser = {
to: userEmail,
subject: mail.subject,
body: mail.body,
};
await fetch(`/api/sendEmail`, {
method: `POST`,
headers: { 'Content-Type': `application/json` },
body: JSON.stringify(mailToUser),
});
console.log(mailToUser);
}
export default sendEmail;
Run Code Online (Sandbox Code Playgroud)
这是单击按钮时需要调用以发送邮件的自定义挂钩文件
contact.tsx
import sendEmail from 'src'
export const Contact = (props:any) {
const userName = `Name`;
const userEmail = `email`;
const userPhone = `333333333`;
return (
<button onClick={() => sendEmail(userName, userEmail, userPhone)}>Contact</button>
)
}
Run Code Online (Sandbox Code Playgroud)
当我点击按钮时出现的错误是:
**Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:**
Pra*_*kal 12
你不能像错误所说的那样直接使用钩子,但在你的情况下,这通常是一个方法,这不是一个钩子。
如果您正在管理其中的某种state/context内部内容来管理应用程序工作流程和数据,基本上钩子会很有用。但如果您只想发送电子邮件,则不需要任何类型的挂钩。您可以简单地创建一个方法并调用该方法。
就像这里的例子:
// app.js
const sendEmail = async (email, subject, body) => {
const mailToUser = {
to: email,
subject: subject,
body: body
};
await fetch(`/api/sendEmail`, {
method: `POST`,
headers: { "Content-Type": `application/json` },
body: JSON.stringify(mailToUser)
});
console.log(mailToUser);
};
export default function App() {
return (
<div className="App">
<button onClick={() => sendEmail("test@gmail.com", "subject", "body")}>
Send Email
</button>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
但如果你想实现一个钩子,你可以简单地这样做:
// useEmail.js
const useEmail = () => {
const sendEmail = async (email, subject, body) => {
const mailToUser = {
to: email,
subject: subject,
body: body
};
await fetch(`/api/sendEmail`, {
method: `POST`,
headers: { "Content-Type": `application/json` },
body: JSON.stringify(mailToUser)
});
console.log(mailToUser);
};
return { sendEmail };
};
export default useEmail;
Run Code Online (Sandbox Code Playgroud)
在你的组件中你可以实现它:
// app.js
import useEmail from "./hook/sendEmail";
export default function App() {
const { sendEmail } = useEmail();
return (
<div className="App">
<button onClick={() => sendEmail("test@gmail.com", "subject", "body")}>
Send Email
</button>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9019 次 |
| 最近记录: |