动态 href 标签 React in JSX.

Dynamic href tag React in JSX

本文关键字:in JSX React 标签 href 动态      更新时间:2023-09-26
// This Javascript <a> tag generates correctly
React.createElement('a', {href:"mailto:"+this.props.email}, this.props.email)

但是,我正在努力在 JSX 中重新创建它

<a href="mailto: {this.props.email}">{this.props.email}</a>
// => <a href="mailto: {this.props.email}"></a>

href 标签认为{this.props.email}是一个字符串,而不是动态输入 {this.props.email} 的值。关于我哪里出了问题的任何想法?

它返回一个字符串,因为您要将其分配给字符串。

您需要将其设置为动态属性,该属性的开头包含一个字符串

<a href={"mailto:" + this.props.email}>email</a>

一种稍微更ES6的方法来执行Patrick的建议,方法是使用模板文字:

<a href={`mailto:${this.props.email}`}>email</a>

在我看来,更好的方法是将其拆分为函数和JSX attr,如下所示:

  <Button
    onClick=sendMail
  >
    Send mail
  </Button>
const sendMail = () => {
  const mailto: string =
    "mailto:mail@gmail.com?subject=Test subject&body=Body content";
  window.location.href = mailto;
}

我认为这可能很容易...试试吧

<a href={`mailto:${email}?subject=${subject}&body=${text}`}>{email}</a>