react 不用插件,渲染json数据成markdown

renderMarkDown = str => {

let object = {};

try {

object = JSON.parse(str);

} catch (err) {

console.log(err)

}

return this.renderObject(object)

}

renderObject = (object) => {

switch (typeof (object)) {

case "string":

return <span style={{ color: "#D14" }}>{`"${object}"`}</span>

case "object":

if (Array.prototype.isPrototypeOf(object)) {

return <span >

<span>{'['}</span>

{object.map((item, index) => <span key={index}>

{this.renderObject(item)}

<span>{index < Object.keys(object).length - 1 ? "," : ""}</span>

</span>)}

<span>{']'}</span>

</span>

} else if (Object.prototype.isPrototypeOf(object)) {

return <span>

<span>{'{'}</span>

{Object.keys(object).map((item, index) => <div key={index} style={{ marginLeft: "16px", whiteSpace: "pre" }}>

<span style={{ marginRight: "4px" }}>{`"${item}"`}:</span>

{this.renderObject(object[item])}

<span>{index < Object.keys(object).length - 1 ? "," : ""}</span>

</div>)}

<span>{'}'}</span>

</span>

} else if (object === null) {

return <span style={{ color: "#099" }}>{"null"}</span>

}

default:

return <span style={{ color: "#099" }}>{object}</span>

}

}


版权声明:本文为sinat_34209942原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。