[英]Dynamic href tag React in JSX
// This Javascript <a> tag generates correctly
React.createElement('a', {href:"mailto:"+this.props.email}, this.props.email)
However, I'm struggling to recreate it in JSX但是,我正在努力在 JSX 中重新创建它
<a href="mailto: {this.props.email}">{this.props.email}</a>
// => <a href="mailto: {this.props.email}"></a>
The href tag thinks the {this.props.email}
is a string instead of dynamically inputting the value of {this.props.email}
. href 标签认为
{this.props.email}
是一个字符串,而不是动态输入{this.props.email}
的值。 Any ideas on where I went amiss?关于我哪里出错的任何想法?
It is returning a string because you are assigning it to a string.它返回一个字符串,因为您将它分配给一个字符串。
You'll want to set it to a dynamic property, that includes a the string at the beginning of it您需要将其设置为动态属性,其中包含开头的字符串
<a href={"mailto:" + this.props.email}>email</a>
一个稍微多一点 ES6 的方式来做 Patrick 的建议是使用模板文字:
<a href={`mailto:${this.props.email}`}>email</a>
A nicer way to do this in my opinion will be to split it into a function and a JSX attr, something like that:在我看来,一个更好的方法是将它拆分为一个函数和一个 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.