简体   繁体   English

在 JSX 表达式中连接字符串和 HTML

[英]Concatenate a string and HTML Inside JSX Expression

I'm trying to concatenate a string and HTML inside a JSX expression, but I can't seem to do it correctly.我正在尝试在 JSX 表达式中连接字符串和 HTML,但我似乎无法正确执行此操作。 The code in my render function looks like this:我的渲染函数中的代码如下所示:

<span>
   {'preferred string' || `Other string ${<a target="_blank" href={someVariable}>text inside link</a>}`}
</span>

What I want it to render is: "Other string text inside link"我希望它呈现的是:“链接内的其他字符串文本”

What it actually renders is "Other string [object Object]"它实际呈现的是“其他字符串[对象对象]”

I've tried a few different strategies but am having no luck.我尝试了几种不同的策略,但没有运气。 Any advice is greatly appreciated.任何意见是极大的赞赏。

You want something along the lines of:你想要一些类似的东西:

<span>
  {'preferred string' || <p>Other string <a target="_blank" href={variable}>text inside</a></p>}
</span>

The key thing is the paragraph tags are added.关键是添加了段落标签。 In your code, React is struggling to interpret multiple different languages at the same time.在您的代码中,React 正在努力同时解释多种不同的语言。

Keep in mind that this solution will, similar to the code that you gave, only show the second result if the 'preferred string' is empty or null, and as is, it is hard-coded to have some value, so the second half of the or statement will never show.请记住,此解决方案将与您提供的代码类似,仅在“首选字符串”为空或空时才显示第二个结果,并且按原样进行硬编码以具有某些值,因此后半部分的 or 语句永远不会显示。

Edit: if your strings are in fact variables, then you'll need to exit again for 'other string' like so:编辑:如果您的字符串实际上是变量,那么您需要再次退出“其他字符串”,如下所示:

<span>
  { stringVariable || <p>{otherStringVariable}<a target="_blank" href={variable}>{insideTextVariable}</a></p> }
</span>

If you want only to concatenate the string with a tag, you can try this simple way:如果您只想将字符串与标签连接起来,您可以尝试这种简单的方法:

<>
    preferred string || Other string <a target="_blank" href={someVariable}>text inside link</a>
</>

or, something like this:或者,像这样:

<span>
       {'preferred string' || <span>Other string <a target="_blank" href={someVariable}>text inside link</a></span>}
</span>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM