在React中连接变量和字符串 [英] Concatenating variables and strings in React
问题描述
有没有将React的大括号符号和 href
标签合并的方法?假设我们在状态中有以下值:
Is there a way to incorporate React's curly brace notation and an href
tag? Say we have the following value in the state:
{this.state.id}
以及标签上的以下HTML属性:
and the following HTML attributes on a tag:
href="#demo1"
id="demo1"
我可以将 id
状态添加到HTML属性中,以获得如下所示的结果:
Is there a way I can add the id
state to the HTML attribute to get something like this:
href={"#demo + {this.state.id}"}
其中将产生:
Which will yield:
#demo1
推荐答案
你几乎是正确的,只是放错了几个引号。用正则引号将整个东西包装起来就会给你字符串 #demo + {this.state.id}
- 你需要指出哪些是变量,哪些是字符串。由于 {}
内的任何内容都是内嵌的JSX 表达式,因此您可以这样做:
You're almost correct, just misplaced a few quotes. Wrapping the whole thing in regular quotes will literally give you the string #demo + {this.state.id}
- you need to indicate which are variables and which are string literals. Since anything inside {}
is an inline JSX expression, you can do:
href={"#demo" + this.state.id}
<这将使用字符串文字 #demo
,并将其连接到 this.state.id
的值。这可以应用于所有字符串。考虑一下:
This will use the string literal #demo
and concatenate it to the value of this.state.id
. This can then be applied to all strings. Consider this:
var text = "world";
与此:
And this:
{"Hello " + text + " Andrew"}
This will yield:
Hello world Andrew
您也可以使用ES6字符串插值/ template literals with`(backticks)and $ {expr}
(内插表达式),这更接近您似乎试图要做:
You can also use ES6 string interpolation/template literals with ` (backticks) and ${expr}
(interpolated expression), which is closer to what you seem to be trying to do:
href={`#demo${this.state.id}`}
这将基本上替代 this.state.id
的值,将它连接起来到 #demo
。它相当于:#demo+ this.state.id
。
This will basically substitute the value of this.state.id
, concatenating it to #demo
. It is equivalent to doing: "#demo" + this.state.id
.
这篇关于在React中连接变量和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!