动态创建一个由N个ListItemTexts组成的ListItem

问题描述

在谷歌搜索时找不到任何有用的线索后,在此处与新手联系。

给出一个数据列表,其中每个数据描述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>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...