2019-09-24
描述
根据 type
属性来创建不同的提示组件。
- 为组件中的元素定义适当的 CSS 样式和动画
- 使用
React.setState()
hook 创建isShown
和isLeaving
状态变量,并设置他们的默认值为false
- 定义
timeoutId
用来保存计时器实例,以便在组件卸载时进行清除 - 使用
React.setEffect()
hook 更新isShown
的值为true
,当组件卸载时清除使用过的timeoutId
- 定义
closeNotification
方法,通过setTimeout()
将isShown
设置为false
。这样当提示框通过动画消失后就可将组件从 DOM 中移除 - 定义一个组件,该组件使用用户定义的
message
进行渲染,其中关闭按钮可以让该组件从 DOM 中移除
实现
@keyframes leave { 0% { opacity: 1 } 100% { opacity: 0 } } .alert { padding: 0.75rem 0.5rem; margin-bottom: 0.5rem; text-align: left; padding-right: 40px; border-radius: 4px; font-size: 16px; position: relative; } .alert.warning{ color: #856404; background-color: #fff3cd; border-color: #ffeeba; } .alert.error{ color: #721c24; background-color: #f8d7da; border-color: #f5c6cb; } .alert.leaving{ animation: leave 0.5s forwards; } .alert .close { position: absolute; top: 0; right: 0; padding: 0 0.75rem; color: #333; border: 0; height: 100%; cursor: pointer; background: none; font-weight: 600; font-size: 16px; } .alert .close:after{ content: 'x'; }
function Notification(props) { const [isShown, setIsShown] = React.useState(false); const [isLeaving, setIsLeaving] = React.useState(false); let timeoutId = null; React.useEffect(() => { setIsShown(true); return () => { clearTimeout(timeoutId); } }, [props.isShown, props.timeout, timeoutId]); const closeNotification = () => { setIsLeaving(true); timeoutId = setTimeout(() => { setIsLeaving(false); setIsShown(false); }, 250) } return isShown && ( <div className={`alert ${props.type}${isLeaving ? ' leaving' : ''}`} role="alert"> <button className="close" onClick={closeNotification} /> {props.message} </div> ) }
使用
ReactDOM.render(<Notification type="info" message="This is info" />, document.getElementById('root'));
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于