在这种情况下,什么是“生成”?

时间:2018-11-19 17:41:49

标签: javascript reactjs

在以下情况下,generate()方法是什么意思,它如何工作?我以前从未见过。这是List组件的一种方法,还是属于React.js或JSX或属于Javascript还是属于其他内容?我还没有找到任何相关文档。

demo.js文件in this codesandbox contains the following

https://codesandbox.io/s/ppmxj46w8x

demo.js,从第115行开始
      <Grid item xs={12} md={6}>
        <Typography variant="h6" className={classes.title}>
          Avatar with text
        </Typography>
        <div className={classes.demo}>
          <List dense={dense}>
            {generate(  // <-- what is this?
              <ListItem>
                <ListItemAvatar>
                  <Avatar>
                    <FolderIcon />
                  </Avatar>
                </ListItemAvatar>
                <ListItemText
                  primary="Single-line item"
                  secondary={secondary ? 'Secondary text' : null}
                />
              </ListItem>,
            )}
          </List>
        </div>
      </Grid>

Here are the docs the code sandbox comes from.

有人可以解释一下,并向我指出有关此generate()方法的一些文档。

1 个答案:

答案 0 :(得分:2)

它正在为传入的元素创建键值对:

function generate(element) {
  return [0, 1, 2].map(value =>
    React.cloneElement(element, {
      key: value, // value = 0, 1, 2
    }),
  );
}

例如,在第82行(它只是附加一个键):

<ListItem key={value}>
  <ListItemText
    primary="Single-line item"
    secondary={secondary ? 'Secondary text' : null}
  />
</ListItem>

翻译为:

<ListItem key={0}>
  <ListItemText
    primary="Single-line item"
    secondary={secondary ? 'Secondary text' : null}
  />
</ListItem>
<ListItem key={1}>
  <ListItemText
    primary="Single-line item"
    secondary={secondary ? 'Secondary text' : null}
  />
</ListItem>
<ListItem key={2}>
  <ListItemText
    primary="Single-line item"
    secondary={secondary ? 'Secondary text' : null}
  />
</ListItem>