在React/JSX中显示嵌套的JSON可以通过以下步骤实现:
const nestedJSON = {
name: "John",
age: 30,
address: {
street: "123 Main St",
city: "New York",
country: "USA"
},
hobbies: ["reading", "traveling", "coding"]
};
import React from "react";
const NestedJSONComponent = ({ data }) => {
const renderNestedJSON = (data) => {
return Object.entries(data).map(([key, value]) => {
if (typeof value === "object") {
return (
<div key={key}>
<strong>{key}: </strong>
<NestedJSONComponent data={value} />
</div>
);
} else if (Array.isArray(value)) {
return (
<div key={key}>
<strong>{key}: </strong>
{value.map((item, index) => (
<span key={index}>{item}, </span>
))}
</div>
);
} else {
return (
<div key={key}>
<strong>{key}: </strong>
{value}
</div>
);
}
});
};
return <div>{renderNestedJSON(data)}</div>;
};
export default NestedJSONComponent;
import React from "react";
import NestedJSONComponent from "./NestedJSONComponent";
const App = () => {
const nestedJSON = {
name: "John",
age: 30,
address: {
street: "123 Main St",
city: "New York",
country: "USA"
},
hobbies: ["reading", "traveling", "coding"]
};
return (
<div>
<h1>Nested JSON Example</h1>
<NestedJSONComponent data={nestedJSON} />
</div>
);
};
export default App;
这样,嵌套的JSON数据就会在React/JSX中被正确地显示出来。对于嵌套的对象,会递归地创建新的NestedJSONComponent组件来显示;对于数组,会使用map函数遍历并显示每个元素。
领取专属 10元无门槛券
手把手带您无忧上云