👋 欢迎回到《前端达人 · 播客书单》第 5 期(正文内容为学习笔记摘要,音频内容是详细的解读,方便你理解),请点击下方收听
📌 今天我们不再停留在看代码,而是动手实现一个真正的 React 组件:带关闭功能的 Alert 提示框。如果你已经知道什么是 JSX、Props 和 State,那么今天这期内容将帮助你把这些拼图拼到一起!
🔧 第一步:做一个基本的 Alert 组件
还记得 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>
);
}
💡 提示:
JSX 里 class 叫 className。
图标加上
role="img"
和aria-label
,提升无障碍支持。组件名必须大写!不然 React 会把它当成原生 HTML 标签。
🎨 第二步:加点“定制味道” —— 用 Props 做组件参数化
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
;条件渲染用
&&
,真值就渲染,假值就忽略。
📦 第四步:组件记住“关闭”状态 —— 用 State 控制可见性
让按钮真正“管用”,我们得用上 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 组件为什么要以大写开头?
JSX 中怎么嵌入变量?
Props 和 State 的区别是啥?
什么是条件渲染?
如果你都能答出来,那你真的已经掌握了本节核心!
#React #前端播客 #前端达人 #React播客专栏