REACT - toggle class onclick

后端 未结 14 1965
长情又很酷
长情又很酷 2020-11-27 11:40

I am trying to figure out how to toggle an active class onClick to change CSS properties.

I have taken many approaches, and read many SO answers. Using

14条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 12:12

    I started learning React recently and wanted to build a tab just to see how far my knowledge has gone. I came across this and decided to implement something without redux. I kind of feel the answers don't reflect what op wants to achieve. He wants only one active component but the answers here will set all components active. I have given it a shot.

    Below is a tab file

    import React, { Component } from 'react';
    
    
    class Tab extends Component {
    
        render(){
            const tabClassName = "col-xs-3 tab-bar";
            const activeTab = this.props.activeKey === this.props.keyNumber ? "active-tab" : null;
            return (
                    
    this.props.onClick(this.props.keyNumber)} > I am here
    ); } } export default Tab;

    The tabs file...

    import React, { Component } from 'react';
    import Tab from './tab';
    
    class Tabs extends Component {
    
        constructor(props){
            super(props);
    
            this.state = {
                currentActiveKey: 0,
                tabNumber: 2
            };
    
            this.setActive = this.setActive.bind(this);
            this.setTabNumber = this.setTabNumber.bind(this);
        }
    
        setTabNumber(number){
            this.setState({
                tabNumber: number
            });
        }
    
        setActive (key){
            this.setState({
                currentActiveKey: key 
            });
        }
    
        render(){
            let tabs = [];
            for(let i = 0; i <= this.state.tabNumber; i++){
                let tab = ;
                tabs.push(tab);
            }
            return (
                
    {tabs}
    ); } } export default Tabs;

    your index file...

    import React from 'react';
    import ReactDOM from 'react-dom';
    import Tabs from './components/tabs';
    
    
    ReactDOM.render(
        
      , document.querySelector('.container'));
    

    and the css

    .tab-bar {
        margin: 10px 10px;
        border: 1px solid grey;
    }
    
    .active-tab {
        border-top: 1px solid red;
    }
    

    This is a skeleton of something I want to improve on so increasing the tabNumber beyond 4 will break the css.

提交回复
热议问题