问题描述
在谷歌搜索时找不到任何有用的线索后,在此处与新手联系。
给出一个数据列表,其中每个数据描述ListItem
应该包含的内容,如何动态创建并返回ListItems列表?每个ListItem
都不同(例如,有些按钮,有些则没有)
const listData = [
{
"isClickable":true,"horizontalComponents":[
{
"type": "image","data": {
"url": "http://tiny.co/foobar123"
}
},{
"type": "text","componentData": {
"content": "This is a descriptive text. To view more please click the button on the right."
}
},{
"type": "button","componentData": {
"buttonString": "View More"
}
}
]
}
];
listData.forEach(itemData => {
var columns: typeof ListItemText[] = [];
itemData.horizontalComponents.forEach(component => {
if (component.type == "text") {
columns.push(
<ListItemText primary={`Line item foo`} />
)
}
})
})
解决方法
反应组件将数组作为子级接受,因此您可以选择使用map
返回数组ListItem
const listData = [
{
"isClickable": true,"horizontalComponents": [
{
"type": "image","data": {
"url": "http://tiny.co/foobar123"
}
},{
"type": "text","componentData": {
"content": "This is a descriptive text. To view more please click the button on the right."
}
},{
"type": "button","componentData": {
"buttonString": "View More"
}
}
]
}
];
function App() {
return (
<List>
{listData.map((listitem,index) => (
<ListItem key={index}>
{listitem.horizontalComponents.map((component,index) => {
if (component.type === "text") {
return (
<ListItemText key={index}>{component.componentData.content}</ListItemText>
);
} else if (component.type === "button") {
return <Button key={index} variant="contained">{component.componentData.buttonString}</Button>;
}
})}
</ListItem>
))}
</List>
);
}
ReactDOM.render(<App/>,document.getElementById("root"));
<body>
<div id="root"></div>
<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>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js"></script>
<script type="text/babel">
const { List,ListItem,ListItemText,Button } = MaterialUI;
</script>
</body>