[英]tab menu corresponding button active
您好,我现在正在制作标签菜单。 我的问题是我想在单击按钮时给出 is-active ,但我不知道在那里的空白处放置什么值。
type Props = {
title: string
index: number
setSelectedTab: (index: number) => void
}
const TabTitle: React.FunctionComponent<Props> = ({ title, setSelectedTab, index }) => {
// The value to be activated. Initial value is `0th button`
const [activeIndex, setActiveIndex] = useState(0);
const onClick = useCallback(() => {
setSelectedTab(index)
}, [setSelectedTab, index])
return (
<li>
<button
key={index}
className={activeIndex === [empty place] ? "is-active" : ""}
onClick={() => onClick()}
>
{title}
</button>
</li>
)
}
console.log(index);
// 0
// 1
// 2
索引值如何使用If you click the 0th button, index: 0
If you click the 1st button, index: 1
做成这样后, className={activeIndex === index? "is-active": ""}
className={activeIndex === index? "is-active": ""}
如果你放index
,它会正常工作,但我不知道如何制作这样的索引。
如何根据点击值设置索引以给予第一次点击 0 第二次点击 1?
您需要将index
属性与selectedTab
属性(可能存在于父组件上,因为您将setSelectedTab
function 传递给TabTitle
组件)进行比较。
import { useCallback } from "react";
type Props = {
title: string;
index: number;
selectedTab: number; // <-- this should be passed by the parent
setSelectedTab: (index: number) => void;
};
const TabTitle: React.FunctionComponent<Props> = ({
title,
selectedTab,
setSelectedTab,
index
}) => {
const onClick = useCallback(
(index) => {
setSelectedTab(index);
},
[setSelectedTab]
);
return (
<li>
<button
key={index}
className={selectedTab === index ? "is-active" : ""} // it's active if its index is the same as the selected tab
onClick={() => onClick(index)} // <-- so it knows which button was clicked
>
{title}
</button>
</li>
);
};
export default TabTitle;
您可以在代码沙箱上看到一个简单的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.