JSX中动态href标签的React

34
// 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} 的值。有任何想法在哪里我错了吗?


这是很酷的东西。 - Araali Farooq
4个回答

63

它返回一个字符串,因为你将其赋值给了一个字符串。

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

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


45

按照 Patrick 建议的方式,稍微更 ES6 的做法是使用模板字面量:

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


4

在我看来,更好的方法是将它拆分为函数和JSX属性,就像这样:

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

0

我认为这可能非常简单...试一下

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

如果您能解释一下这个解决方案是如何解决问题的,以及它与已经发布在这里的答案有何不同,那将会更加有帮助。 - camille

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接