反应::标签

呈现选项卡式菜单和视图组件。

定义一个 TabItem 组件,将其传递给,Tab 并TabItem 通过在中标识该函数的名称 来 删除不必要的节点 props.children。使用  挂钩将 状态变量的值初始化 为 。使用  收集到的节点上呈现  和 。定义 ,这将点击时要执行  从 。  执行传递的回调  并进行更新 ,这又将导致重新渲染, 并 根据项目和 按钮 的 和对其  进行 评估 。React.useState()bindIndexprops.defaultIndexArray.prototype.maptab-menutab-viewchangeTab<button>tab-menuchangeTabonTabClickbindIndexstyleclassNametab-viewtab-menuindex

.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;
}
function TabItem(props) {
  return <div {...props} />;
}

function Tabs(props) {
  const [bindIndex, setBindIndex] = React.useState(props.defaultIndex);
  const changeTab = newIndex => {
    if (typeofprops.onTabClick=== "function") props.onTabClick(newIndex);
    setBindIndex(newIndex);
  };
  const items = props.children.filter(item => item.type.name === "TabItem");

  return (
    <div className="wrapper">
      <div className="tab-menu">
        {items.map(({ props: { index, label } }) => (
          <button
            onClick={() => changeTab(index)}
            className={bindIndex === index ? "focus" : ""}
          >
            {label}
          </button>
        ))}
      </div>
      <div className="tab-view">
        {items.map(({ props }) => (
          <div
            {...props}
            className="tab-view_item"
            key={props.index}
            style={{ display: bindIndex ===props.index? "block" : "none" }}
          />
        ))}
      </div>
    </div>
  );
}
ReactDOM.render(
  <Tabs defaultIndex="1" onTabClick={console.log}>
    <TabItem label="A" index="1">
      Lorem ipsum
    </TabItem>
    <TabItem label="B" index="2">
      Dolor sit amet
    </TabItem>
  </Tabs>,
  document.getElementById("root")
);