gpt4 book ai didi

javascript - React JSON 模式双引号编码

转载 作者:行者123 更新时间:2023-12-04 12:44:13 24 4
gpt4 key购买 nike

我正在开发一个需要定义 json-ld 模式的 React 应用程序。我通过 API 获取架构字符串,并且需要将适当的脚本标签添加到我的页面。

我的架构字符串看起来像这样:

[{"@context": "http://schema.org"}]

我希望这将被翻译成:
<script type="application/ld+json">
[{"@context": "http://schema.org"}]
</script>

但是,我在处理双引号时遇到了麻烦,因为它们会转换为等效的 html - &quot;
这就是我的代码的样子:
schemaString = "[{\"@context\": \"http://schema.org\"}]";

render() {
return (<div>{schemaString &&
<script type="application/ld+json">
{schemaString}
</script>}
</div>)
}

生成的html是:
<div>
<script type="application/ld+json">
[{&quot;@context&quot;: &quot;http://schema.org&quot;}]
</script>
</div>

关于我在这里缺少什么的任何指示?谢谢!

最佳答案

我迟了吗? :) 确保通过 dangerouslySetInnerHTML 放置脚本标记内容属性(property)。另外,不要忘记通过 JSON.stringify() 将默认对象转换为正确的 JSON。方法。
像这样:

return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(yourSchemaObject) }}
/>
);

关于javascript - React JSON 模式双引号编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49018148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com