简体   繁体   English

使用ES6模板链接的文本

[英]Text with a link using ES6 template

I would like to show "I read and agree to the privacy policy.privacy policy." 我想表明“我阅读并同意隐私政策。隐私政策。” text and the 'privacy policy' part of it must be a link. 文本和“隐私政策”部分必须是一个链接。

I tried below but output is "I read and agree to the [object object]." 我在下面尝试但是输出是“我读并同意[对象对象]。”

const privacyLink = <a href="">Privacy Policy</a>;
{`I read and agree to the ${privacyLink}`}

How can I do this using string template? 如何使用字符串模板执行此操作?

privacyLink is missing quotes. privacyLink缺少引号。 The template literal syntax is not correct. 模板文字语法不正确。 Define privacyLink as a string, define a separate template literal including privacyLink . privacyLink定义为字符串,定义包含privacyLink的单独模板文字。

 const privacyLink = "<a href=>Privacy Policy</a>"; const template = `I read and agree to the ${privacyLink}`; document.body.innerHTML += template; 

or simply define privacyLink as a string and use += operator and .innerHTML to set the .innerHTML of an element within document 或者只是将privacyLink定义为字符串,并使用+=运算符和.innerHTML来设置document元素的.innerHTML

 const privacyLink = "I read and agree to the <a href=>Privacy Policy</a>"; document.body.innerHTML += privacyLink; 

Your question is missing the JSX tag, but you're clearly using JSX syntax so I'll answer it based on that interpretation. 您的问题是缺少JSX标记,但您显然正在使用JSX语法,因此我将基于该解释来回答它。

When you write JSX, you're actually telling your transpiler to create a function, eg if you're using JSX with React, then 当您编写JSX时,您实际上是在告诉您的转换器创建一个函数,例如,如果您将JSX与React一起使用,那么

<a href="">Privacy Policy</a>

is

React.createElement('a', { href: '' }, 'Privacy Policy');

And the createElement returns on object, which is what's showing in your string template. 并且createElement返回对象,这是在字符串模板中显示的内容。

You can use string templates for building strings, so anything that you include inside the ${} must be a string, or it will be cast as a string. 您可以使用字符串模板来构建字符串,因此您在${}包含的任何内容都必须是字符串,否则它将被转换为字符串。

You should continue to use JSX syntax for writing anything you want to include another JSX element. 您应该继续使用JSX语法来编写您想要包含另一个JSX元素的任何内容。 This can be a bit tricky, since any element tree needs to have a root element. 这可能有点棘手,因为任何元素树都需要有一个根元素。 Generally you're pretty safe to use a <span> , so in this case: 一般来说,使用<span>非常安全,所以在这种情况下:

<span>I read and agree to the {privacyLink}</span>

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

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