Javascript JSX 中的动态 href 标签 React

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34779642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:50:31  来源:igfitidea点击:

Dynamic href tag React in JSX

javascriptreactjsreact-jsx

提问by thedanotto

// 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}. Any ideas on where I went amiss?

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

回答by Patrick

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>

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

回答by Sean Clancy

A slightly more ES6 way to do what Patrick is suggesting would be to use a template literal:

一个稍微多一点 ES6 的方式来做 Patrick 的建议是使用模板文字:

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

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