内容简介:本文译自:选项卡组件。例子
本文译自: 30-seconds-of-react 。 React 30 秒速学: 精选有用的 React 片段,30-seconds-of-react 的中文版本,已全部完成翻译、上线,地址: 30-seconds-of-react-zh_CN-umi 。
选项卡组件。
-
定义一个
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>
);
}
复制代码
例子
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>
);
}
复制代码
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。