【问题标题】:How to trigger a custom hook on onClick event in react如何在反应中触发 onClick 事件的自定义钩子
【发布时间】:2022-01-05 14:04:34
【问题描述】:

我想调用一个自定义钩子,它会在单击按钮时发送电子邮件。

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;

这是点击按钮时需要调用发送邮件的自定义钩子文件

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

点击按钮时出现的错误是:

**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:**

【问题讨论】:

标签: reactjs react-hooks next.js typescript-typings


【解决方案1】:

你不能像错误所说的那样直接使用钩子,但在你的情况下,这通常是一个方法,这不是一个钩子。

如果您在其中管理某种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>
  );
}

但如果你想实现一个钩子,你可以简单地这样做:

// 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;

你可以在你的组件中实现它:

// 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>
  );
}

【讨论】:

    【解决方案2】:

    看起来customHook.ts实际上并不是一个钩子, 阅读 Hooks 规则React hook Rules

    【讨论】:

      猜你喜欢
      • 2020-01-12
      • 1970-01-01
      • 2019-05-27
      • 2019-06-15
      • 2020-03-08
      • 2020-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多