在React中编写可重用模态的最佳方法是什么?



我正在用React + Material UI编写一个应用程序。在我的应用程序中,不同的页面上有使用模态的动作,而不是在每个页面上使用材质UI的对话框,我定义了一个全局模态上下文,它改变状态以显示并填充其他道具的模态。现在我的问题是,渲染这些道具的标准做法是什么?也就是说,在什么时候我应该决定创建一个单独的模式/对话框,比如窗体,而不是简单的动作?或者它是正确的,如果我使用条件渲染任何东西和一切从一个模态?作为一个例子,考虑以下示例:

<DialogContent>
<DialogContentText>
{modalTypeDefaults.text}
</DialogContentText>
<DialogContentText sx={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
marginTop: '5px'
}}>
{
(modalTypeDefaults.type === 'user')
? <UserInfoCellComponent displayName={modalProps.displayName} imageURL={modalProps.fkImageIdAvatar} username={modalProps.username.toLowerCase()} />
: (modalTypeDefaults.type === 'post')
? <Box>
<Typography>Title: {modalProps.title.toUpperCase()}</Typography>
<Typography>Id: {modalProps.id}</Typography>
</Box>
: (modalTypeDefaults.type === 'event')
? <Box
sx={{
alignItems: 'center',
display: 'flex'
}}
>
<Avatar
src={modalProps.fkImageId}
sx={{ mr: 2 }}
/>
<Typography
color="textPrimary"
variant="body1"
>
<a href={modalProps.urlWebsite}>{modalProps.name}</a>
</Typography>
</Box>
: ''
}
</DialogContentText>
</DialogContent>

有标准的做法吗?我环顾四周,发现了各种各样的答案。

我以前使用的一种方法是将所有这些都包装在上下文中,然后使用useContext()提供自定义钩子来修改状态。这样,你就可以在代码的任何地方更新这些道具了。

最新更新