React add class active on selected tab

后端 未结 2 1789
无人共我
无人共我 2021-02-20 01:23

I have the following:

var Tab = React.createClass({
    getInitialState: function(){
        return {
          selected:\'\'
        }
    },
    activateTab: f         


        
2条回答
  •  无人及你
    2021-02-20 01:44

    Necro poster here. Cool answer up above!

    In any way, here is the 2018 upgrade answer with recompose and styled-components. You can even make a HOC out of it for a joyful reusability!

    https://codesandbox.io/s/1826454zl7

    import React from "react";
    import ReactDOM from "react-dom";
    import { compose, withState, withHandlers } from "recompose";
    import styled from "styled-components";
    
    const enhancer = compose(
      withState("selectedTabId", "setSelectedTabId", 1),
      withHandlers({
        isActive: props => id => {
          return props.selectedTabId === id;
        },
        setActiveTab: props => id => {
          props.setSelectedTabId(id);
        }
      })
    );
    
    const Tabs = enhancer(props => {
      return (
        
      {props.data.map((el, i) => { return ( props.setActiveTab(el.id)} /> ); })}
    ); }); const Tab = props => { return (

    {props.content}

    ); }; const StyledLi = styled.li` font-weight: ${({ isActive }) => (isActive ? 600 : 100)}; cursor: pointer; font-family: Helvetica; transition: 200ms all linear; `; const data = [ { id: 1, name: "tab-1", text: "text" }, { id: 2, name: "tab-2", text: "text-2" }, { id: 3, name: "tab-3", text: "text-2" } ]; const ExampleApp = () => ; ReactDOM.render(, document.getElementById("app"));

    Basic idea is that you need to get selected index, map over the item on every click, compare selected index with all other indexes and return true to props of a needed component if the match is found.

提交回复
热议问题