从另一个组件调用函数

时间:2019-08-16 13:52:10

标签: javascript reactjs

我有我的文件:

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
import ListItemText from '@material-ui/core/ListItemText';
import AuthentificationService from "../../api/AuthentificationService"
import IconButton from '@material-ui/core/IconButton';
import DeleteIcon from '@material-ui/icons/Delete';
import ModifyUser from "./ModifyUser" ----------> file i import where my function is

const useStyles = makeStyles(theme => ({
    root: {
        width: '100%',
        maxWidth: 360,
        backgroundColor: theme.palette.background.paper,
    },
}));

export default function CheckboxList(props) {
    const classes = useStyles();
    const [checked, setChecked] = React.useState([0]);

    const handleToggle = value => () => {
        const currentIndex = checked.indexOf(value);
        const newChecked = [...checked];

        if (currentIndex === -1) {
            newChecked.push(value);
        } else {
            newChecked.splice(currentIndex, 1);
        }

        setChecked(newChecked);

        alert(value.email)
    };

    const deleteUser = value => () => {
        AuthentificationService.deleteUser(value.id)
            .then((data) => {
            console.log(data);

        }) .catch((error) => {
            console.log(error)
        })
        handleClickOpen(); ---------> here i would like to call this function from the file ./ModifyUser
    }

    return (
        <List className={classes.root}>
            {props.response.map( test => {

                if (props.response.length <= 1) {

                } else {
                    return (
                        <ListItem key={test} role={undefined} dense button onClick={handleToggle(test)}>
                            <ListItemText primary={`${test.email}`}/>
                            <ListItemSecondaryAction>
                                <IconButton edge="end" aria-label="delete">
                                    <DeleteIcon
                                        onClick={deleteUser(test)}
                                    />
                                </IconButton>
                            </ListItemSecondaryAction>
                            <ModifyUser/>
                        </ListItem>
                    );
                }
            })}
        </List>
    );
}

我想从文件./ModifyUser中调用handleClickOpen。​​

文件修改用户为:

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import ListItem from '@material-ui/core/ListItem';
import List from '@material-ui/core/List';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import IconButton from '@material-ui/core/IconButton';
import Typography from '@material-ui/core/Typography';
import CloseIcon from '@material-ui/icons/Close';
import Slide from '@material-ui/core/Slide';
import TextField from "@material-ui/core/TextField";
import AuthentificationService from "../../api/AuthentificationService";

const useStyles = makeStyles(theme => ({
    appBar: {
        position: 'relative',
    },
    title: {
        marginLeft: theme.spacing(2),
        flex: 1,
    },
}));

const Transition = React.forwardRef(function Transition(props, ref) {
    return <Slide direction="up" ref={ref} {...props} />;
});

export default function FullScreenDialog() {
    const classes = useStyles();
    const [open, setOpen] = React.useState(false);
    let username = "";
    let email = "";
    let password = "";

    function handleClickOpen() {   ---------> i would like to call this function
        setOpen(true);
    }

    function handleClose() {
        setOpen(false);
    }

    /// Set the state when the texfield change
    function textFieldChange(e) {
        if (e.target.id.localeCompare("Username") === 0) {
            username = e.target.value;

        }  else if (e.target.id.localeCompare("Email") === 0) {
            email = e.target.value;
        }  else if (e.target.id.localeCompare("Password") === 0) {
            password = e.target.value;
        }
    }

    async function handleSubmit() {
        alert(email);
        alert(password);
        try {
            await AuthentificationService.addUser({
                username: username;
            })  .then((data) => {
                console.log(data)
            })
        } catch (error) {
            console.log(error)
        }
    }

    return (
        <div>
            <Dialog fullScreen open={open} onClose={handleClose} TransitionComponent={Transition}>
                <AppBar className={classes.appBar}>
                    <Toolbar>
                        <IconButton edge="start" color="inherit" onClick={handleClose} aria-label="close">
                            <CloseIcon />
                        </IconButton>
                        <Typography variant="h6" className={classes.title}>
                            New User
                        </Typography>
                        <Button color="inherit" onClick={() => {
                            handleSubmit();
                            handleClose();
                        }}>
                            YES
                        </Button>
                    </Toolbar>
                </AppBar>
                <List>
                    <ListItem button>
                        <TextField className="fontLogin"
                                   onChange={textFieldChange}
                                   label="Username"
                                   style={{width: '55%'}}
                                   id="Username"
                        />
                    </ListItem>
                </List>
            </Dialog>
        </div>
    );
}

我想在另一个文件中调用该文件的handleClickOpen。​​

当我调用它时,出现错误“不存在”。

我导入了我的文件,所以他为什么找不到它?

也许是在不同的班级里,所以我应该有吸气剂或类似的东西吗?

我误会了什么?

2 个答案:

答案 0 :(得分:0)

一些初步想法:

您似乎在“导出”中导出了很多功能。您是否尝试过移动功能,然后导出文件本身,而不是导出功能?

此外,handleClickOpen()也写在FullScreenDialogue()内部。这使我认为要调用它,您将必须首先调用FullScreenDialogue ---您将不能将handleClickOpen作为独立函数来调用。

答案 1 :(得分:0)

首先,您的函数handleClickOpen属于FullScreenDialog类,因此您应该导入此类:

import FullScreenDialog from "./ModifyUser";

第二,handleClickOpen函数管理组件的状态,该组件必须呈现在某个位置才能调用其功能。如果您想在组件渲染之前调用此函数(或触发组件渲染),可以尝试制作此函数static,但是您不能使用函数中的this上下文(包括组件的状态)。