简体   繁体   English

如何将 JSX 存储在变量中?

[英]How can I store JSX in a variable?

This outputs correctly, works as JSX, highlights the field as expected.这输出正确,作为 JSX 工作,按预期突出显示该字段。

var result = "the text";
renderResults[2].props.children.props.listing.title = <span className="highlight"> {result} </span>;

This one, however, does not.然而,这个没有。 It displays as a string with the html tags:它显示为带有 h​​tml 标签的字符串:

var result = "the text";
var finalResult = <span className="highlight"> {result} </span>;
renderResults[2].props.children.props.listing.title = finalResult;

How do I get the second to pass as JSX and not a string?如何让第二个作为 JSX 而不是字符串传递?

您的类属性缺少结束语

var finalResult = <span className="highlight"> {result} </span>;

You didn't close className, maybe that is the reason why it doesn't work.您没有关闭 className,也许这就是它不起作用的原因。

className="highlight"类名=“突出显示”

There is a small typo on your code, you are missing a " after className="highlight>您的代码有一个小错误,您在className="highlight>之后缺少一个"

A working example:一个工作示例:

 const Demo = () => { const result = "the text"; const finalResult = <span className="highlight"> {result} </span>; return finalResult; } ReactDOM.render(<Demo/>, document.getElementById('demo'))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script> <div id="demo"></div>

Correct me if I'm mistaken, but as mentioned per docs here如果我弄错了,请纠正我,但正如此处的每个文档所述

By default, React DOM escapes any values embedded in JSX before rendering them.默认情况下,React DOM 会在呈现 JSX 中嵌入的任何值之前对其进行转义。 Thus it ensures that you can never inject anything that's not explicitly written in your application.因此,它确保您永远不会注入任何未在您的应用程序中明确写入的内容。 Everything is converted to a string before being rendered.在渲染之前,所有内容都被转换为字符串。 This helps prevent XSS (cross-site-scripting) attacks.这有助于防止 XSS(跨站点脚本)攻击。

So it assumes that your variable is user input or something malicious and escapes it before using it's content, while in the second example, you're explicitly assigning JSX to a variable so it works.因此,它假定您的变量是用户输入或恶意内容,并在使用其内容之前对其进行转义,而在第二个示例中,您将 JSX 显式分配给变量以使其工作。

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

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