将JSX对象转换为字符串
我在.jsx文件中有一个对象,其中包含jsx.ements。我想将其转换为字符串,例如从此转换为:
const data = {
title: 'Create cat',
description: 'Creates a new cat',
react_element: (
<>
<span>Create account body here</span>
<VideoEmbed title="Youtube sample" description="This is a spiderman meme" videoLink="https://www.youtube.com/embed/FKPiqAFt3Rk" />
</>
),
generatePrettyReactElement: (args: string) => (
<>
<span>Create account body here</span>
<VideoEmbed title="Youtube sample" description="This is a spiderman meme" videoLink="https://www.youtube.com/embed/FKPiqAFt3Rk" />
</>
),
};
我
const string = "const data = { title: 'Create cat', description: 'Creates a new cat', react_element: (<> <span>Create account body here</span> <VideoEmbed title="Youtube sample" description="This is a spiderman meme" videoLink="https://www.youtube.com/embed/FKPiqAFt3Rk" /> </>),generatePrettyReactElement: (args: string) => (<> <span>Create account body here</span><VideoEmbed title="Youtube sample" description="This is a spiderman meme" videoLink="https://www.youtube.com/embed/FKPiqAFt3Rk" /></>),};"
尝试了json.stringify(data)
,但随后丢失了jsx.elements,然后我尝试了 https://www.npmjs.com/package/reaect-eleact-element-to-jsx-string ,但它仅适用于JSX.Element,而不是可能包含JSX元素的对象。
I have an object in .jsx file that contains JSX.elements here and there. I want to convert it to string, e.g go from this:
const data = {
title: 'Create cat',
description: 'Creates a new cat',
react_element: (
<>
<span>Create account body here</span>
<VideoEmbed title="Youtube sample" description="This is a spiderman meme" videoLink="https://www.youtube.com/embed/FKPiqAFt3Rk" />
</>
),
generatePrettyReactElement: (args: string) => (
<>
<span>Create account body here</span>
<VideoEmbed title="Youtube sample" description="This is a spiderman meme" videoLink="https://www.youtube.com/embed/FKPiqAFt3Rk" />
</>
),
};
To this:
const string = "const data = { title: 'Create cat', description: 'Creates a new cat', react_element: (<> <span>Create account body here</span> <VideoEmbed title="Youtube sample" description="This is a spiderman meme" videoLink="https://www.youtube.com/embed/FKPiqAFt3Rk" /> </>),generatePrettyReactElement: (args: string) => (<> <span>Create account body here</span><VideoEmbed title="Youtube sample" description="This is a spiderman meme" videoLink="https://www.youtube.com/embed/FKPiqAFt3Rk" /></>),};"
I've tried JSON.stringify(data)
but then it loses JSX.elements, then I've tried https://www.npmjs.com/package/react-element-to-jsx-string but it only works with JSX.Element and not an object that might contain JSX elements.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以为JSON.Stringify函数编写替换器,并为每个JSX元素使用React-Element to-jsx-string。
You can write replacer for JSON.stringify function and use react-element-to-jsx-string for each JSX element.