使用 textarea 中的正文响应打开 mailto 电子邮件客户端 onClick

Cod*_*ife 6 mailto reactjs

这听起来好像以前肯定有人问过,但我只能在 react native 中找到如何做到这一点,但在正常 react for web 中我找不到它是如何做到的。最好不要使用需要样式化的标签或链接标签。

这里有一些代码来说明我想要做什么:

const onClickMailtoHandler = () => {
    //TODO: open default e-mail client e.g. via mailto link with text from (state) variable as body
}

<Button onClick={onClickMailtoHandler}>Send E-Mail</Button>
Run Code Online (Sandbox Code Playgroud)

以下是如何在 HTML 中创建 mailto 链接:

<a href="mailto:max.mustermann@example.com?body=My custom mail body">E-Mail to Max Mustermann</a>
Run Code Online (Sandbox Code Playgroud)

Cod*_*xer 16

我使用以下方法在单击按钮时打开默认邮件客户端:

<button onClick={() => window.location = 'mailto:yourmail@domain.com'}>Contact Me</button>
Run Code Online (Sandbox Code Playgroud)

  • 将其与 React、nextJs 和 TS 一起使用时,出现错误:“类型‘字符串’不可分配给类型‘位置’。”将“window.location”更改为“window.location.href”有效。 (4认同)

Cod*_*ife 9

我最终创建了一个类似于@GitGitBoom 在评论中建议的组件。

在这里为未来的寻求者:

import React from "react";
import { Link } from "react-router-dom";

const ButtonMailto = ({ mailto, label }) => {
    return (
        <Link
            to='#'
            onClick={(e) => {
                window.location = mailto;
                e.preventDefault();
            }}
        >
            {label}
        </Link>
    );
};

export default ButtonMailto;
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

<ButtonMailto label="Write me an E-Mail" mailto="mailto:no-reply@example.com" />
Run Code Online (Sandbox Code Playgroud)