在 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}"}
哪个会产生:
#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";
还有这个:
{"Hello " + text + " Andrew"}
这将产生:
Hello world Andrew
您还可以使用 ES6 字符串插值/模板文字 带有 `(反引号)和 ${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屋!