【问题标题】:tab menu corresponding button active选项卡菜单对应按钮激活
【发布时间】:2022-01-20 01:10:30
【问题描述】:

您好,我现在正在制作标签菜单。 我的问题是我想在单击按钮时给出 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" : ""} 放上index 就可以正常工作了,但是不知道怎么做这样的索引。

如何根据点击的值设置索引给第一次点击0 第二次点击1?

【问题讨论】:

    标签: javascript reactjs ecmascript-6 react-hooks


    【解决方案1】:

    您需要将index 属性与selectedTab 属性(它可能存在于父组件上,因为您将setSelectedTab 函数传递给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;
    

    您可以在代码框上看到simple example

    【讨论】:

    • 你好,这是一个额外的问题,但我有一个问题要问。如果我想在标题部分放置不同的黑白图像。当标题变为活动状态时,我正在尝试将其变成彩色图像,您能给我一个提示吗....对不起
    • 是的,如果您的图像一开始是全彩色的,这很容易。然后,您可以在 CSS grayscale 过滤器不活动时应用它们。我已经更新了example 来展示它是如何工作的。
    • 你真是个天才。如果像你这样的人是公司的导师,我会很高兴。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 2015-06-06
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多