漂亮的印刷JSON与反应 [英] Pretty Printing JSON with React
问题描述
我正在使用ReactJS,我的应用程序的一部分需要相当印刷的JSON。
I'm using ReactJS and part of my app requires pretty printed JSON.
我得到一些JSON,如: {foo:1,bar:2}
,如果我在浏览器控制台中通过 JSON.stringify(obj,null,4)
运行它,它很漂亮,但是当我在这个反应片段中使用它时:
I get some JSON like: { "foo": 1, "bar": 2 }
, and if I run that through JSON.stringify(obj, null, 4)
in the browser console, it pretty prints, but when I use it in this react snippet:
render: function() {
var json = this.getStateFromFlux().json;
return (
<div>
<JsonSubmitter onSubmit={this.onSubmit} />
{ JSON.stringify(json, null, 2) }
</div>
);
},
它呈现看起来像的总JSON{ \foo \:2,\bar \:2} \ n
。
如何正确解释这些字符? {
How do I get those characters to be interpreted properly? {
推荐答案
您需要在适当的位置插入 BR
标签结果字符串,或使用例如 PRE
标记,以便保留 stringify
的格式:
You'll need to either insert BR
tag appropriately in the resulting string, or use for example a PRE
tag so that the formatting of the stringify
is retained:
var data = { a: 1, b: 2 };
var Hello = React.createClass({
render: function() {
return <div><pre>{JSON.stringify(data, null, 2) }</pre></div>;
}
});
React.render(<Hello />, document.getElementById('container'));
工作示例。
class PrettyPrintJson extends React.Component {
render() {
// data could be a prop for example
// const { data } = this.props;
return (<div><pre>{JSON.stringify(data, null, 2) }</pre></div>);
}
}
ReactDOM.render(<PrettyPrintJson/>, document.getElementById('container'));
这篇关于漂亮的印刷JSON与反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!