React JSON 模式双引号编码

San*_*wat 5 javascript schema.org reactjs json-ld

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

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

[{"@context": "http://schema.org"}]
Run Code Online (Sandbox Code Playgroud)

我希望这会被翻译成:

<script type="application/ld+json">
   [{"@context": "http://schema.org"}]                    
</script>
Run Code Online (Sandbox Code Playgroud)

然而,我在处理双引号时遇到了麻烦,因为它们被转换为等效的 html -&quot;

这就是我的代码的样子:

schemaString = "[{\"@context\": \"http://schema.org\"}]";

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

生成的html为:

<div>
  <script type="application/ld+json">
    [{&quot;@context&quot;: &quot;http://schema.org&quot;}]
  </script>
</div>
Run Code Online (Sandbox Code Playgroud)

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

小智 6

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

像这样:

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


小智 1

schemaString = [{ "@context": "http://schema.org" }];
render() {
    return (
        <div>
            {schemaString &&
                <script type="application/ld+json">
                    {JSON.stringify(schemaString)}
                </script>
            }
        </div>)
}
Run Code Online (Sandbox Code Playgroud)