react实现active高亮的两种方式

702 阅读1分钟

前端开发中经常要给样式添加高亮,这里提供了 react 添加高亮的两种实现方式

通过class实现

image.png 安装第三方包

pnpm add classnames --save

定义样式

.active {
  @apply bg-secondary-color text-white;
}

使用

...
export interface IProps {
  tabNames: string[] | undefined
}

// memo浅层比较
const SectionTabs: FC<IProps> = memo(function (props) {
  const { tabNames } = props

  // 定义选中的标签
  const [currentIndex, setCurrentIndex] = useState(1)

  // item点击
  function itemClickHandle(index: number) {
    setCurrentIndex(index)
  }

  return (
    <div className="flex">
      {tabNames?.map((item, index) => {
        return (
          <div
            className={classNames(...',
              { active: currentIndex === index }
            )}
            key={item}
            onClick={(e) => itemClickHandle(index)}
          >
            {item}
          </div>
        )
      })}
    </div>
  )
})

通过style实现

image.png

...
export interface IProps {
  tabNames: string[] | undefined
}

// memo浅层比较
const SectionTabs: FC<IProps> = memo(function (props) {
  const { tabNames } = props

  // 定义选中的标签
  const [currentIndex, setCurrentIndex] = useState(1)

  // item点击
  function itemClickHandle(index: number) {
    setCurrentIndex(index)
  }

  return (
    <div className="flex">
      {tabNames?.map((item, index) => {
        return (
          <div
            className="..."
            style={
              currentIndex === index
                ? { background: '#00848A', color: '#fff' }
                : {}
            }
            key={item}
            onClick={(e) => itemClickHandle(index)}
          >
            {item}
          </div>
        )
      })}
    </div>
  )
})