JSX 中的动态 href 标签 React
Dynamic href tag React in JSX
// 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>
按照 Patrick 的建议,一种稍微更加 ES6 的方法是使用模板文字:
<a href={`mailto:${this.props.email}`}>email</a>
在我看来,更好的方法是将其拆分为一个函数和一个 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;
}
// 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>
按照 Patrick 的建议,一种稍微更加 ES6 的方法是使用模板文字:
<a href={`mailto:${this.props.email}`}>email</a>
在我看来,更好的方法是将其拆分为一个函数和一个 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;
}