【问题标题】:Adding Dynamic States to React JS project向 React JS 项目添加动态状态
【发布时间】:2021-09-20 07:33:37
【问题描述】:

我正在创建一个emojipedia 应用程序,当按下表情符号时,它预计会打开一个包含表情符号描述的Modal。据我所知,为此,我需要将表情符号的描述(包含在emojipedia.js 文件中)映射到Components 文件夹中的EmojiContainer 组件。

我的问题来了,当我按下表情符号时,它会被绞死。为什么会发生这种情况以及如何解决?

提前致谢。

【问题讨论】:

  • 你好。如果需要帮助,至少需要提供一些示例代码。
  • 我已经在那里提供了代码和框链接。

标签: reactjs material-ui


【解决方案1】:

您在EmojiContainer 上使用单一状态来控制表情符号列表中的所有模式。因此,当您尝试打开模式时,所有模式都会打开。更好的选择是将与单个模态相关的所有逻辑封装在一个单独的、可重用的组件中:

export default function Emoji({ item }) {
  const [open, setOpen] = useState(false);
  return (
    <Grid item lg={2} md={3} xs={6}>
      <ImageButton onClick={() => setOpen(true)}>
        <CardMedia
          sx={{
            "&:hover": {
              transform: "scale(1.3)"
            }
          }}
          component="img"
          height="100"
          image={item.link}
          alt="emoji"
        />
      </ImageButton>
      <Modal
        open={open}
        onClose={() => setOpen(false)}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
      >
        <Typography sx={style} variant="p">
          {item.desc}
        </Typography>
      </Modal>
    </Grid>
  );
}

如您所见,此组件有自己的状态并控制自己的模式。在您的 EmojiContainer 中,您可以像这样使用它:

export default function EmojiContainer() {
  return (
    <Grid>
      {emojipedia.map((item, index) => (
        <Grid key={index} container>
          <Emoji item={item} />
        </Grid>
      ))}
    </Grid>
  );
}

据我所知,您还需要调整模态样式。这是更新后的codesandbox

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 2021-03-16
    相关资源
    最近更新 更多