【问题标题】:Dynamic href tag React in JSXJSX 中的动态 href 标签 React
【发布时间】:2016-04-19 04:36:22
【问题描述】:
// 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}的值。关于我哪里出错的任何想法?

【问题讨论】:

  • 这是很酷的员工..

标签: javascript reactjs react-jsx


【解决方案1】:

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

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

&lt;a href={"mailto:" + this.props.email}&gt;email&lt;/a&gt;

【讨论】:

    【解决方案2】:

    Patrick 建议的一个稍微更多的 ES6 方法是使用模板文字:

    &lt;a href={`mailto:${this.props.email}`}&gt;email&lt;/a&gt;

    【讨论】:

      【解决方案3】:

      在我看来,更好的方法是将其拆分为一个函数和一个 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;
      }
      

      【讨论】:

        猜你喜欢
        • 2020-09-11
        • 2021-08-06
        • 2020-09-22
        • 2017-05-27
        • 2020-08-12
        • 2017-05-28
        • 2017-05-28
        相关资源
        最近更新 更多