👋 欢迎回到《前端达人 · 播客书单》第 5 期(正文内容为学习笔记摘要,音频内容是详细的解读,方便你理解),请点击下方收听
📌 今天我们不再停留在看代码,而是动手实现一个真正的 React 组件:带关闭功能的 Alert 提示框。如果你已经知道什么是 JSX、Props 和 State,那么今天这期内容将帮助你把这些拼图拼到一起!
还记得 React 的核心逻辑吗?组件就是一个函数,返回 JSX,就能控制 UI 输出。
function Alert() {
return (
<div>
<div>
<span role="img" aria-label="Warning">⚠</span>
<span>Oh no!</span>
</div>
<div>Something isn't quite right ...</div>
</div>
);
}
💡 提示:
role="img"
和 aria-label
,提升无障碍支持。Alert 不应该只显示“⚠ Oh no!” 吧?我们来让它变得灵活:
export function Alert({ type = "information", heading, children }) {
return (
<div>
<div>
<span role="img" aria-label={type === "warning" ? "Warning" : "Info"}>
{type === "warning" ? "⚠" : "ℹ️"}
</span>
<span>{heading}</span>
</div>
<div>{children}</div>
</div>
);
}
👀 使用方式变得很灵活:
<Alert type="information" heading="Success">
Everything is really good!
</Alert>
✔️ 小技巧:
children
就是你写在组件标签之间的内容;type
, heading
, children
都是通过 Props 来配置;用户想关掉 Alert 怎么办?来,我们加个 closable
属性。
{closable && (
<button aria-label="Close">
<span role="img" aria-label="Close">❌</span>
</button>
)}
这样就能控制这个按钮是否显示了!
在使用时只要这样写:
<Alert type="warning" heading="Oops" closable>
Something went wrong!
</Alert>
✅ 注意:
closable
只要写上就等于 true
;&&
,真值就渲染,假值就忽略。让按钮真正“管用”,我们得用上 useState
:
import { useState } from"react";
exportfunction Alert({ type = "info", heading, children, closable }) {
const [visible, setVisible] = useState(true);
if (!visible) returnnull;
const handleCloseClick = () => setVisible(false);
return (
<div>
<div>
<span>{type === "warning" ? "⚠" : "ℹ️"}</span>
<span>{heading}</span>
</div>
<div>{children}</div>
{closable && (
<button onClick={handleCloseClick}>❌</button>
)}
</div>
);
}
🎯 一句话总结:点一下关闭按钮,visible 变成 false,Alert 消失!
如果你都能答出来,那你真的已经掌握了本节核心!
#React #前端播客 #前端达人 #React播客专栏
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有