首页 > 解决方案 > 如何使用 React Hooks 在 React 中填充对话

问题描述

我需要使用 Material UI 对话框显示一些信息。在 useEffect 钩子中调用 handleOpen 函数会在页面打开时默认打开对话框。有人可以帮助告诉我如何仅在单击按钮时填充对话框吗?请注意,postId 是作为来自父组件的 props 传递的。提前致谢

 import { useState, useEffect } from 'react'
 import { useSelector, useDispatch } from 'react-redux'

 import { getSinglePost } from '../../store/actions/postActions'

 //MUI Components
 import { Dialog, DialogHeader, Button, DialogContent, DialogActions, Grid, Typography, IconButton} 
 from '@material-ui/core'
 import LaunchIcon from '@material-ui/icons/Launch';


const PostDialog = ({postId}) => {
    const [ open, setOpen ] = useState(false)

    const post = useSelector(state => state.posts.post)

    const dispatch = useDispatch()

    useEffect(() => {
       handleOpen()
    }, [])


const handleOpen = () => {
    setOpen({ open: true })
    dispatch(getSinglePost(postId))
}

const handleClose = () => {
    setOpen({ open: false })
}

return (
    <div>
        <Button onClick={handleOpen}>
            <LaunchIcon fontSize="small" color="primary" />
        </Button>
        <Dialog
        open={open}
        onClose={handleClose} 
        fullWidth
        maxWidth="sm"
        >
            <DialogContent>
                <Grid container>
                    <Grid item sm={5}>
                        {/* <img src={userImage} width="150" /> */}
                    </Grid>
                    <Grid>
                    <Typography variant="h6">@{post.handle}</Typography>
                    <Typography variant="h6">{post.job_title}</Typography>
                    <Typography variant="body2">{post.long_description}</Typography>

                    </Grid>


                </Grid>
            </DialogContent>

        </Dialog>
        
      </div>
   )
 }


 export default PostDialog

标签: reactjsdialogmaterial-uiuse-effect

解决方案


推荐阅读