格式化 JSON为字符串,并在页面上显示
PrintJSON.js
import React from 'react';
import PropTypes from 'prop-types';
import styled from './index.module.less';
const JsonStringify = data => JSON.stringify(data, null, 2);
PrintJson.propTypes = {
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object,
]),
};
PrintJson.defaultProps = {
value: '',
}
function PrintJson({ value }) {
if([null, undefined, false].includes(value)) return null;
let data = '';
if(typeof value === 'string') {
try {
data = JSON.parse(value);
} catch (e) {
data = value;
}
}
return (
<div className={styled.wrap}>
<pre className={styled.print}>
{(typeof data === 'string') ? data : JsonStringify(data)}
</pre>
</div>
);
}
export default React.memo(PrintJson);
index.module.less
.wrap {
margin-bottom: 16px;
padding: 16px;
background-color: rgba(245, 245, 245, .5);
}
.print {
width: 100%;
white-space: pre-wrap;
word-wrap: break-word;
}