本文译自:30-seconds-of-react 。 React 30 秒速学: 精选有用的 React 片断,30-seconds-of-react 的中文版本,已所有完成翻译、上线,地址:30-seconds-of-react-zh_CN-umi 。css
系列文章:react
TabItem
组件,将它传递给Tab
并经过在props.children
中识别函数的名称来删除除了TabItem
外的没必要要的节点。React.useState()
hook 将bindIndex
状态变量的值初始化为props.defaultIndex
。Array.prototype.map
来渲染tab-menu
和tab-view
。changeTab
,用于 tab-menu
单击 <button>
时执行。index
反过来从新渲染 tab-view
项的style
和className
以及tab-menu
。changeTab
执行传递的回调函数 onTabClick
,并更新 bindIndex
,这会致使从新渲染,根据它们的 index
改变 tab-view
项目和 tab-menu
按钮的 style
和 className
。.tab-menu > button {
cursor: pointer;
padding: 8px 16px;
border: 0;
border-bottom: 2px solid transparent;
background: none;
}
.tab-menu > button.focus {
border-bottom: 2px solid #007bef;
}
.tab-menu > button:hover {
border-bottom: 2px solid #007bef;
}
复制代码
import styles from "./Tabs.css";
function TabItem(props) {
return <div {...props} />;
}
function Tabs(props) {
const [bindIndex, setBindIndex] = React.useState(props.defaultIndex);
const changeTab = newIndex => {
if (typeof props.onTabClick === "function") props.onTabClick(newIndex);
setBindIndex(newIndex);
};
const items = props.children.filter(item => item.type.name === TabItem.name);
return (
<div className={styles["wrapper"]}>
<div className={styles["tab-menu"]}>
{items.map(({ props: { index, label } }) => (
<button
onClick={() => changeTab(index)}
key={index}
className={bindIndex === index ? styles["focus"] : ""}
>
{label}
</button>
))}
</div>
<div className={styles["tab-view"]}>
{items.map(({ props }) => (
<div
{...props}
className={styles["tab-view_item"]}
key={props.index}
style={{ display: bindIndex === props.index ? "block" : "none" }}
/>
))}
</div>
</div>
);
}
复制代码
例子git
export default function() {
return (
<Tabs defaultIndex="1" onTabClick={console.log}> <TabItem label="A" index="1"> A 选修卡的内容 </TabItem> <TabItem label="B" index="2"> B 选修卡的内容 </TabItem> </Tabs>
);
}
复制代码