我已经为警告框编写了以下钩子:
import MuiAlert from '@material-ui/lab/Alert';
import { Snackbar } from '@material-ui/core';
import React from 'react';
export const useAlert = () => {
const [open, setOpen] = React.useState(false);
const [message, setMessage] = React.useState('');
const openAlert = (message) => {
setOpen(true);
setMessage(message);
};
const closeAlert = (event, reason) => {
setOpen(false);
};
return {
openAlert,
Alert: <Snackbar open={open} onClose={closeAlert}><MuiAlert onClose={closeAlert}>{ message }</MuiAlert></Snackbar>
};
};
然后我将这个钩子集成到其他功能组件中,如下所示:
import { useAlert } from './useAlert';
const Dashboard = () => {
const { openAlert, Alert } = useAlert();
return (
<div>{ Alert }</div>
)
};
我知道从 React hooks 返回 函数组件 是不好的做法,因为钩子将在每次渲染时生成组件的新实例。
但是,在这里,我返回的是 JSX 元素而不是组件。 这仍然是不好的做法吗?