嗨,我设计了这个警报组件:
import React from 'react';
import { Alert } from 'antd';
export default function CustomAlert (props) {
return (
<React.Fragment>
{
props.visible ?
<Alert message={props.message} style={{textAlign: 'right', direction: 'rtl' , position: 'fixed', width:'100%', zIndex:'100'}} closable afterClose={props.handleClose}/>
:
null
}
</React.Fragment>
)
}
但我想在 5 秒后隐藏警报。我该怎么做?
答案 0 :(得分:2)
您可以使用 setTimeout 来自动关闭类似这样的警报。找到工作示例 here
export default function CustomAlert(props) {
const [visible, setVisible] = React.useState(props.visible);
React.useEffect(() => {
visible &&
setTimeout(() => {
setVisible(false);
}, props.closeAfter);
}, [props.closeAfter, visible, setVisible]);
return (
<React.Fragment>
{visible ? (
<Alert
message={props.message}
style={{
textAlign: "right",
direction: "rtl",
position: "fixed",
width: "100%",
zIndex: "100"
}}
closable
afterClose={props.handleClose}
/>
) : null}
</React.Fragment>
);
}
并在其他文件中使用这样的组件,
<CustomAlert visible message="Test Message" closeAfter={5000} />
答案 1 :(得分:0)
我用这种风格解决了我的问题:
.alert{
-moz-animation: cssAnimation 0s ease-in 15s forwards;
/* Firefox */
-webkit-animation: cssAnimation 0s ease-in 15s forwards;
/* Safari and Chrome */
-o-animation: cssAnimation 0s ease-in 15s forwards;
/* Opera */
animation: cssAnimation 0s ease-in 15s forwards;
-webkit-animation-fill-mode: forwards;
animation-fill-mode: forwards;
text-align: right ;
direction: rtl ;
position: fixed;
width: 100% ;
z-index: 100;
}
@keyframes cssAnimation {
to {
width:0;
height:0;
overflow:hidden;
z-index: -100;
}
}
@-webkit-keyframes cssAnimation {
to {
width:0;
height:0;
visibility:hidden;
z-index: -100;
}
}
答案 2 :(得分:0)
我用 css 样式发布了一个答案,但这里有一个更好的答案:
import React, {useEffect} from 'react';
import { Alert } from 'antd';
export default function CustomAlert(props) {
useEffect(() => {
setInterval(() => {
props.handleClose();
},5000 )
}, [])
return (
<React.Fragment>
{props.visible ? (
<Alert
message={props.message}
style={{
textAlign: "right",
direction: "rtl",
position: "fixed",
width: "100%",
zIndex: "100"
}}
closable
afterClose={props.handleClose}
/>
) : null}
</React.Fragment>
);
}