我在React中编写了一个组件,最后,我编写了一个返回component的函数。 现在,我想通过在我的React应用程序上调用该函数来显示组件
我的组件代码是:
import React from 'react';
import { Snackbar as MuiSnackbar, IconButton } from '@material-ui/core'
import { Close as CloseIcon, CheckCircle as CheckCircleIcon, Error as ErrorIcon, Info as InfoIcon, Warning as WarningIcon } from '@material-ui/icons'
import styled from 'styled-components';
import { green, amber, red, blue } from '@material-ui/core/colors';
const toastBgColor = {
success: green[600],
warning: amber[700],
error: red[400],
info: blue[200]
}
const toastIcons = {
success: <CheckCircleIcon />,
warning: <WarningIcon />,
error: <ErrorIcon />,
info: <InfoIcon />
}
const Wrapper = styled(MuiSnackbar)`
background-color: ${props => toastBgColor[props.bg]};
`
const Snackbar = (props) => {
const [toastError, setToastError] = React.useState(true)
const handleClose = (event, reason) => {
if (reason === 'clickaway') {
return;
}
setToastError(false);
};
return (
<Wrapper
anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}
open={toastError}
autoHideDuration={5000}
onClose={handleClose}
ContentProps={{
'aria-describedby': 'message-id',
}}
message={<span id="message-id">{toastIcons[props.bg]}{props.message}</span>}
action={[
<IconButton
key="close"
aria-label="close"
color="inherit"
onClick={handleClose}
>
<CloseIcon />
</IconButton>,
]}
/>
);
}
export default (bg,message)=><Snackbar bg={bg} message={message}/>
首先,我的组件是Snackbar,最后一行是我的函数。
现在我想通过导入顶级组件(例如从“ top comp”导入Snackbar)
和
调用这样的函数:在我的应用程序中Snackbar(“ success”,“ message”),该组件将运行。
答案 0 :(得分:0)
我理解您的想法,但是我认为这不是解决React中问题的正确方法。
我认为您来自Android背景,您可以直接调用静态方法来显示Snackbar,但这不是React中的工作方式。
在React中,您需要在某个位置渲染Snackbar并通过在空值和其他可能输入的值之间更改toastError
道具来切换它。