REACTJS 将变量插入插值字符串

问题描述 投票:0回答:2

大家好

我正在尝试在 ReactJS 中创建一个链接,并传递一个搜索字符串。我想要创造的是

<td><Link to={{pathname: '/select_item', search: '?item_id=83'}}>Select</Link></td>

其中项目 id(在本例中为 83)被替换为变量“itemId”,该变量在循环中变化。如果我硬编码 itemId(如上面的示例所示),则链接有效。

我试过了

<td><Link to={{pathname: '/select_item'0, search: '?item_id=`${itemId}`'}}>Select</Link></td>

但这不起作用 - itemId 没有被替换,所以链接文本是

/select_item?item_id=${itemId}

然后我尝试了

var path = "pathname: '/approve_item1', search: '?walk_id=" + item.id + "'";
<td><Link to={{path}}>Select</Link></td>

但这也行不通。

我希望这是有道理的!谁能告诉我如何将变量插入插值字符串的秘密?

谢谢,

格雷姆

reactjs interpolation
2个回答
0
投票

您应该将整个字符串用反引号括起来。

<td><Link to={{pathname: '/select_item', search: `?item_id=${itemId}`}}>Select</Link></td>

有关模板字符串的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals


0
投票

我认为你可以使用 String Interpolation 来做到这一点,如下所示:

<td><Link to=`/select_item?item_id=${itemID}`>Select</Link></td>

查看更多说明https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#string_interpolation

© www.soinside.com 2019 - 2024. All rights reserved.