如何在 React 的 onClick 方法中添加 2 个要执行的函数

How to add 2 fuctions to be excuted in onClick method in React

我想知道如何在onClick方法中同时执行2个函数handleClosesaveData

我想执行的地方:

                            <Button variant="contained" onClick={saveData}>
                                Save
                            </Button>

完整代码:

import { useEffect } from "react";
import * as React from "react";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper from "@mui/material/Paper";
import Button from "@mui/material/Button";
import Box from "@mui/material/Box";
import LinearProgress from "@mui/material/LinearProgress";
import Backdrop from "@mui/material/Backdrop";
import Modal from "@mui/material/Modal";
import Fade from "@mui/material/Fade";
import TextField from "@mui/material/TextField";

const style = {
    position: "absolute",
    top: "50%",
    left: "50%",
    transform: "translate(-50%, -50%)",
    width: 400,
    bgcolor: "background.paper",
    border: "2px solid #000",
    boxShadow: 24,
    p: 4,
};

const Home = () => {
    const [data, setData] = React.useState([]);
    const [loader, setLoader] = React.useState(false);
    const [open, setOpen] = React.useState(false);
    const handleOpen = () => setOpen(true);
    const handleClose = () => setOpen(false);

    const [formData, setFormData] = React.useState({
        id: null,
        avatar: "",
        name: "",
    });

    const saveData = () => {
        fetch("https://61924463aeab5c0017105ebe.mockapi.io/test", {
            method: "POST",
            body: JSON.stringify(formData),
            headers: {
                "Content-type": "application/json; charset=UTF-8",
            },
        })
            .then((response) => response.json())
            .then((json) => {
                console.log(json, "Save Data");
                handleClose();
            });
    };

    useEffect(() => {
        setLoader(true);
        fetch("https://61924463aeab5c0017105ebe.mockapi.io/test")
            .then((res) => res.json())
            .then(
                (result) => {
                    if (result) {
                        setData(result);
                        setLoader(false);
                    }
                },
                (error) => {
                    console.log(error);
                }
            );
    }, []);

    console.log(formData);

    return (
        <div>
            <Button variant="contained" onClick={handleOpen}>
                Add
            </Button>
            <br />
            <br />
            {loader ? (
                <LinearProgress />
            ) : (
                <TableContainer component={Paper}>
                    <Table sx={{ minWidth: 650 }} aria-label="simple table">
                        <TableHead>
                            <TableRow>
                                <TableCell align="center">ID</TableCell>
                                <TableCell align="center">Name</TableCell>
                                <TableCell align="center">Avatar</TableCell>
                            </TableRow>
                        </TableHead>
                        <TableBody>
                            {data.map((row) => (
                                <TableRow
                                    key={row.name}
                                    sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
                                >
                                    <TableCell align="center">{row.id}</TableCell>
                                    <TableCell align="center">{row.name}</TableCell>
                                    <TableCell align="center">
                                        <img src={row.avatar} width="25" alt={row.name} />
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </TableContainer>
            )}
            <div>
                <Modal
                    aria-labelledby="transition-modal-title"
                    aria-describedby="transition-modal-description"
                    open={open}
                    onClose={handleClose}
                    closeAfterTransition
                    BackdropComponent={Backdrop}
                    BackdropProps={{
                        timeout: 500,
                    }}
                >
                    <Fade in={open}>
                        <Box sx={style}>
                            <Box
                                component="form"
                                sx={{
                                    "& .MuiTextField-root": { m: 1, width: "25ch" },
                                }}
                                noValidate
                                autoComplete="off"
                            >
                                <div>
                                    <TextField
                                        id="outlined-search"
                                        label="ID"
                                        type="search"
                                        onChange={(text) => {
                                            setFormData({
                                                ...formData,
                                                id: text.target.value,
                                            });
                                        }}
                                    />
                                    <TextField
                                        id="outlined-search"
                                        label="Name"
                                        type="search"
                                        onChange={(text) => {
                                            setFormData({
                                                ...formData,
                                                name: text.target.value,
                                            });
                                        }}
                                    />
                                    <TextField
                                        id="outlined-search"
                                        label="Avatar"
                                        type="search"
                                        onChange={(text) => {
                                            setFormData({
                                                ...formData,
                                                avatar: text.target.value,
                                            });
                                        }}
                                    />
                                </div>
                            </Box>
                            <Button variant="contained" onClick={saveData}>
                                Save
                            </Button>
                        </Box>
                    </Fade>
                </Modal>
            </div>
        </div>
    );
};

export default Home;
<Button variant="contained" onClick={() => {
  saveData();
  handleClose();
}}>
  Save
</Button>

最直接的方法是将它们包装在 jsx prop 中。 如果你不明白我的意思,请看下面的例子:

示例:

import react from "react";

const App = () =>{
return(
    <div id="foo-bar">
        <button onClick={()=>{
            foo()
            foo2();
        }}/>
    </div>
);
}

您可以在 onClick 方法上调用任何处理程序或函数。

实例:

const App = () => {

  const saveData = () => {
    console.log("save data called");
  };

  const handleClose = () => {
    console.log("handleClose");
  };

  const handleOnClick = () => {
    handleClose();
    saveData();
  };

  return (
    <div>
      <button onClick={handleOnClick}>Save</button>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<div id="root"></div>