[英]ReactJS JSX toString()
I'm writing a documentation website based on React. 我正在写一个基于React的文档网站。 I want to show the code that is necessary to use a given component from my framework.
我想展示使用我的框架中给定组件所必需的代码。 At the same time I would like to show the actual component running, like a side-by-side view.
同时我想展示实际的组件运行,就像一个并排的视图。
Currently, I'm adding the component as a String for the reference implementation and the component as JSX for the running scenario. 目前,我将组件添加为参考实现的String,并将组件添加为运行方案的JSX。 Something like this:
像这样的东西:
var ButtonDoc = React.createClass({
render: function () {
let buttonComponent = (
<Button label="Add" />
);
let buttonCode = `<Button label="Add" />`;
return (
<div>
{buttonComponent}
<pre><code>{buttonCode}</code></pre>
</div>
);
}
});
Question: Is there a way that I can get the string representation of the given React component without the need to replicate the code? 问题:有没有办法可以获得给定React组件的字符串表示而无需复制代码?
I'm expecting something like this: 我期待这样的事情:
var ButtonDoc = React.createClass({
render: function () {
let buttonComponent = (
<Button label="Add" />
);
let buttonCode = `${buttonComponent}`;
return (
<div>
{buttonComponent}
<pre><code>{buttonCode}</code></pre>
</div>
);
}
});
The output of the given code is object [object]
. 给定代码的输出是
object [object]
。
As I did not find anything that solved my problem, I ended up creating a npm repository to achieve this task. 由于我没有找到解决我问题的任何内容,我最终创建了一个npm存储库来完成这项任务。
https://github.com/alansouzati/jsx-to-string https://github.com/alansouzati/jsx-to-string
Usage: 用法:
import React from 'react';
import jsxToString from 'jsx-to-string';
let Basic = React.createClass({
render() {
return (
<div />
);
}
}); //this is your react component
console.log(jsxToString(<Basic test1="test" />)); //outputs: <Basic test1="test" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.