[英]Pretty Printing JSON with React
我正在使用 ReactJS 並且我的應用程序的一部分需要漂亮的打印 JSON。
我得到一些 JSON 像: { "foo": 1, "bar": 2 }
,如果我通過JSON.stringify(obj, null, 4)
運行它。在這個反應片段中:
render: function() {
var json = this.getStateFromFlux().json;
return (
<div>
<JsonSubmitter onSubmit={this.onSubmit} />
{ JSON.stringify(json, null, 2) }
</div>
);
},
它呈現看起來像"{ \"foo\": 2, \"bar\": 2}\n"
的總 JSON 。
如何正確解釋這些字符? {
您需要在結果字符串中正確插入BR
標記,或者使用例如PRE
標記,以便保留stringify
的格式:
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'));
const PrettyPrintJson = ({data}) => {
// (destructured) data could be a prop for example
return (<div><pre>{ JSON.stringify(data, null, 2) }</pre></div>);
}
要么, ...
const PrettyPrintJson = ({data}) => (<div><pre>{
JSON.stringify(data, null, 2) }</pre></div>);
(你甚至可能想要使用備忘錄,16.6 +)
const PrettyPrintJson = React.memo(({data}) => (<div><pre>{
JSON.stringify(data, null, 2) }</pre></div>));
只是為了擴展WiredPrairie的答案,一個可以打開和關閉的迷你組件。
可以像:
<Pretty data={this.state.data}/>
export default React.createClass({
style: {
backgroundColor: '#1f4662',
color: '#fff',
fontSize: '12px',
},
headerStyle: {
backgroundColor: '#193549',
padding: '5px 10px',
fontFamily: 'monospace',
color: '#ffc600',
},
preStyle: {
display: 'block',
padding: '10px 30px',
margin: '0',
overflow: 'scroll',
},
getInitialState() {
return {
show: true,
};
},
toggle() {
this.setState({
show: !this.state.show,
});
},
render() {
return (
<div style={this.style}>
<div style={this.headerStyle} onClick={ this.toggle }>
<strong>Pretty Debug</strong>
</div>
{( this.state.show ?
<pre style={this.preStyle}>
{JSON.stringify(this.props.data, null, 2) }
</pre> : false )}
</div>
);
}
});
一種更現代的方法(現在createClass即將推出)
import styles from './DebugPrint.css'
import autoBind from 'react-autobind'
import classNames from 'classnames'
import React from 'react'
export default class DebugPrint extends React.PureComponent {
constructor(props) {
super(props)
autoBind(this)
this.state = {
show: false,
}
}
toggle() {
this.setState({
show: !this.state.show,
});
}
render() {
return (
<div style={styles.root}>
<div style={styles.header} onClick={this.toggle}>
<strong>Debug</strong>
</div>
{this.state.show
? (
<pre style={styles.pre}>
{JSON.stringify(this.props.data, null, 2) }
</pre>
)
: null
}
</div>
)
}
}
和你的風格文件
.root {backgroundColor:'#1f4662'; 顏色:'#ff'; fontSize:'12px'; }
.header {backgroundColor:'#193549'; 填充:'5px 10px'; fontFamily:'monospace'; 顏色:'#ffc600'; }
.pre {display:'block'; 填充:'10px 30px'; 保證金:'0'; 溢出:'滾動'; }
' react-json-view '提供了渲染json字符串的解決方案。
import ReactJson from 'react-json-view';
<ReactJson src={my_important_json} theme="monokai" />
簡短而簡單
<div>
<pre dangerouslySetInnerHTML={{
__html: JSON.stringify(data, null, 2),
}} />
</div>
這是一個基於Chris的回答的反應鈎子中的示例react_hooks_debug_print.html
。 json數據示例來自https://json.org/example.html 。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<!-- Don't use this in production: -->
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script src="https://raw.githubusercontent.com/cassiozen/React-autobind/master/src/autoBind.js"></script>
<script type="text/babel">
let styles = {
root: { backgroundColor: '#1f4662', color: '#fff', fontSize: '12px', },
header: { backgroundColor: '#193549', padding: '5px 10px', fontFamily: 'monospace', color: '#ffc600', },
pre: { display: 'block', padding: '10px 30px', margin: '0', overflow: 'scroll', }
}
let data = {
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": [
"GML",
"XML"
]
},
"GlossSee": "markup"
}
}
}
}
}
const DebugPrint = () => {
const [show, setShow] = React.useState(false);
return (
<div key={1} style={styles.root}>
<div style={styles.header} onClick={ ()=>{setShow(!show)} }>
<strong>Debug</strong>
</div>
{ show
? (
<pre style={styles.pre}>
{JSON.stringify(data, null, 2) }
</pre>
)
: null
}
</div>
)
}
ReactDOM.render(
<DebugPrint data={data} />,
document.getElementById('root')
);
</script>
</body>
</html>
或者按以下方式,將樣式添加到標題中:
<style>
.root { background-color: #1f4662; color: #fff; fontSize: 12px; }
.header { background-color: #193549; padding: 5px 10px; fontFamily: monospace; color: #ffc600; }
.pre { display: block; padding: 10px 30px; margin: 0; overflow: scroll; }
</style>
並使用以下代碼替換DebugPrint
:
const DebugPrint = () => {
// https://stackoverflow.com/questions/30765163/pretty-printing-json-with-react
const [show, setShow] = React.useState(false);
return (
<div key={1} className='root'>
<div className='header' onClick={ ()=>{setShow(!show)} }>
<strong>Debug</strong>
</div>
{ show
? (
<pre className='pre'>
{JSON.stringify(data, null, 2) }
</pre>
)
: null
}
</div>
)
}
const getJsonIndented = (obj) => JSON.stringify(newObj, null, 4).replace(/["{[,\}\]]/g, "")
const JSONDisplayer = ({children}) => (
<div>
<pre>{getJsonIndented(children)}</pre>
</div>
)
然后你可以輕松使用它:
const Demo = (props) => {
....
return <JSONDisplayer>{someObj}<JSONDisplayer>
}
<pre>{JSON.stringify(data, null, 2)}</pre>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.