React:如何防止数据属性中的转义

问题描述 投票:0回答:1

我有一个看起来像这个{“id”:“xyz”,“height”:1024,“width”:1024}的JSON,我希望在数据属性中有:

<div data-command='{"id":"xyz","height":1024,"width":1024}'></div>

但是当我使用react时它会逃脱字符串,如下所示:

<div data-command='{&quot;id&quot;:&quot;xyz&quot;,&quot;height&quot;:1024,&quot;width&quot;:1024}'></div>

我使用此代码生成元素

    React.createElement("div",
{ "data-command" : JSON.stringify({ "id":"xyz", "height":1024, "width":1024 }), null)

有没有人知道如何在没有“逃避?”的情况下获得JSON?

如果不可能,我怎么能在javascript中将其转换回来,以便我可以在之后使用JSON.parse?

javascript json wordpress reactjs wordpress-gutenberg
1个回答
0
投票

'dangerouslySetInnerHTML'属性正好用于这样的场景。

createMarkup() {
    return {__html: `<div data-command='{"id":"xyz","height":1024,"width":1024}'></div>`};
}

render() {
    return (
        <div dangerouslySetInnerHTML={this.createMarkup()}>
        </div>
    );
}
© www.soinside.com 2019 - 2024. All rights reserved.