Javascript REACT - 切换类 onclick

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42630473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:18:24  来源:igfitidea点击:

REACT - toggle class onclick

javascriptreactjs

提问by peter flanagan

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

我想弄清楚如何切换活动类onClick以更改 CSS 属性。

I have taken many approaches, and read many SO answers. Using jquery it would be relatively simple , however, I cannot figure out to do this with react. My code is below. Can anyone advise how I should do this?

我采取了很多方法,并阅读了很多 SO 答案。使用 jquery 会相对简单,但是,我无法弄清楚用 react 来做到这一点。我的代码如下。谁能建议我应该怎么做?

Without creating a new component for each item is it possible to do this?

如果不为每个项目创建一个新组件,是否可以做到这一点?

class Test extends Component(){

    constructor(props) {

    super(props);
    this.addActiveClass= this.addActiveClass.bind(this);

  }

  addActiveClass() {

    //not sure what to do here

  }

    render() {
    <div>
      <div onClick={this.addActiveClass}>
        <p>1</p>
      </div>
      <div onClick={this.addActiveClass}>
        <p>2</p>
      </div>
        <div onClick={this.addActiveClass}>
        <p>3</p>
      </div>
    </div>
  }

}

回答by cssko

Use state. Reacts docs are here.

使用状态。Reacts 文档在这里

class MyComponent extends Component {
    constructor(props) {
        super(props);
        this.addActiveClass= this.addActiveClass.bind(this);
        this.state = {
            active: false,
        };
    }
    toggleClass() {
        const currentState = this.state.active;
        this.setState({ active: !currentState });
    };

    render() {
        return (
            <div 
                className={this.state.active ? 'your_className': null} 
                onClick={this.toggleClass} 
            >
                <p>{this.props.text}</p>
            </div>
        )
  }
}

class Test extends Component {
    render() {
        return (
            <div>
                <MyComponent text={'1'} />
                <MyComponent text={'2'} />
            </div>
        );
    }
}

回答by Jimi Pajala

I would prefer using "&&" -operator on inline if-statement. In my opinnion it gives cleaner codebase this way.

我更喜欢在内联 if 语句中使用 "&&" -operator。在我看来,它以这种方式提供了更清晰的代码库。

Generally you could be doing something like this

通常你可以做这样的事情

render(){
return(
  <div>
    <button className={this.state.active && 'active'}
      onClick={ () => this.setState({active: !this.state.active}) }>Click me</button>
  </div>
)
}

Just keep in mind arrow function is ES6 feature and remember to set 'this.state.active' value in class constructor(){}

请记住箭头函数是 ES6 特性,并记住在类构造函数(){}中设置“this.state.active”值

this.state = { active: false }

or if you want to inject css in JSX you are able to do it this way

或者如果你想在 JSX 中注入 css 你可以这样做

<button style={this.state.active && style.button} >button</button>

and you can declare style json variable

你可以声明样式json变量

const style = { button: { background:'red' } }

remember using camelCase on JSX stylesheets.

记得在 JSX 样式表上使用驼峰命名法。

回答by Bane Bojani?

Well, your addActiveClass needs to know what was clicked. Something like this could work (notice that I've added the information which divs are active as a state array, and that onClick now passes the information what was clicked as a parameter after which the state is accordingly updated - there are certainly smarter ways to do it, but you get the idea).

好吧,您的 addActiveClass 需要知道点击了什么。这样的事情可以工作(请注意,我已将哪些 div 处于活动状态的信息添加为状态数组,并且 onClick 现在将单击的信息作为参数传递,然后状态相应地更新 - 当然有更聪明的方法这样做,但你明白了)。

class Test extends Component(){

  constructor(props) {
    super(props);
    this.state = {activeClasses: [false, false, false]};
    this.addActiveClass= this.addActiveClass.bind(this);
  }

  addActiveClass(index) {
    const activeClasses = [...this.state.activeClasses.slice(0, index), !this.state.activeClasses[index], this.state.activeClasses.slice(index + 1)].flat();
    this.setState({activeClasses});
  }

  render() {
    const activeClasses = this.state.activeClasses.slice();
    return (
      <div>
        <div className={activeClasses[0]? "active" : "inactive"} onClick={() => this.addActiveClass(0)}>
          <p>0</p>
        </div>
        <div className={activeClasses[1]? "active" : "inactive"} onClick={() => this.addActiveClass(1)}>
          <p>1</p>
        </div>
          <div  onClick={() => this.addActiveClass(2)}>
          <p>2</p>
        </div>
      </div>
    );
  }
}

回答by Rizo

using React you can add toggle class to any id/element, try

使用 React,您可以将切换类添加到任何 id/元素,请尝试

style.css

样式文件

.hide-text{
    display: none !important;
    /* transition: 2s all ease-in 0.9s; */
  }
.left-menu-main-link{
    transition: all ease-in 0.4s;
}
.leftbar-open{
    width: 240px;
    min-width: 240px;
    /* transition: all ease-in 0.4s; */
}
.leftbar-close{
    width: 88px;
    min-width:88px;
    transition: all ease-in 0.4s;
}

fileName.js

文件名.js

......
    ToggleMenu=()=>{
             this.setState({
                isActive: !this.state.isActive
              })
              console.log(this.state.isActive)
        }
        render() {
            return (
                <div className={this.state.isActive===true ? "left-panel leftbar-open" : "left-panel leftbar-close"} id="leftPanel">
                    <div className="top-logo-container"  onClick={this.ToggleMenu}>
                            <span className={this.state.isActive===true ? "left-menu-main-link hide-from-menu" : "hide-text"}>Welcome!</span>
                    </div>

                    <div className="welcome-member">
                        <span className={this.state.isActive===true ? "left-menu-main-link hide-from-menu" : "hide-text"}>Welcome<br/>SDO Rizwan</span>
                    </div>
    )
    }
......

回答by dhorelik

React has a concept of components state, so if you want to switch it, do a setState:

React 有组件状态的概念,所以如果你想切换它,做一个setState

constructor(props) {
  super(props);

  this.addActiveClass= this.addActiveClass.bind(this);
  this.state = {
    isActive: false
  }
}

addActiveClass() {
  this.setState({
    isActive: true
  })
}

In your component use this.state.isActiveto render what you need.

在您的组件中用于this.state.isActive渲染您需要的内容。

This gets more complicated when you want to set state in component#1 and use it in component#2. Just dig more into react unidirectional data flow and possibly redux that will help you handle it.

当您想在组件#1 中设置状态并在组件#2 中使用它时,这会变得更加复杂。只需深入研究反应单向数据流和可能帮助您处理它的 redux。

回答by KadoBOT

The above answers will work, but just in case you want a different approach, try classname: https://github.com/JedWatson/classnames

上面的答案会起作用,但如果您想要不同的方法,请尝试使用 classname:https: //github.com/JedWatson/classnames

回答by Alex Jolig

A good samplewould help to understand things better:

一个好的样本将有助于更好地理解事物:

HTML

HTML

<div id="root">
</div>

CSS

CSS

.box {
  display: block;
  width: 200px;
  height: 200px;
  background-color: gray;
  color: white;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
}
.box.green {
  background-color: green; 
}

React code

反应代码

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {addClass: false}
  }
  toggle() {
    this.setState({addClass: !this.state.addClass});
  }
  render() {
    let boxClass = ["box"];
    if(this.state.addClass) {
      boxClass.push('green');
    }
    return(
        <div className={boxClass.join(' ')} onClick={this.toggle.bind(this)}>{this.state.addClass ? "Remove a class" : "Add a class (click the box)"}<br />Read the tutorial <a href="http://www.automationfuel.com" target="_blank">here</a>.</div>       
    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));

回答by Rizo

you can add toggle classor toggle state on click

您可以在单击时添加切换类或切换状态

class Test extends Component(){
  state={
  active:false, 
 }
  toggleClass() {
    console.log(this.state.active)
    this.setState=({
     active:true,
   })
  }

    render() {
    <div>
      <div onClick={this.toggleClass.bind(this)}>
        <p>1</p>
      </div>
    </div>
  }

}

回答by J.Ewa

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.

我最近开始学习 React 并想构建一个选项卡,只是为了看看我的知识已经走了多远。我遇到了这个问题,并决定在没有 redux 的情况下实现一些东西。我有点觉得答案并没有反映 op 想要实现的目标。他只需要一个活动组件,但此处的答案会将所有组件设置为活动状态。我试过了。

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 (
                <div 
                    className = {`${tabClassName} ${activeTab}`}
                    onClick={()=>this.props.onClick(this.props.keyNumber)}
                >
                    I am here
                </div>
        );
    }
}


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 = <Tab key={i} keyNumber={i} onClick={this.setActive} activeKey={this.state.currentActiveKey}/>;
            tabs.push(tab);
        }
        return (
            <div className="row">
                {tabs}
            </div>
        );
    }
}


export default Tabs;

your index file...

你的索引文件...

import React from 'react';
import ReactDOM from 'react-dom';
import Tabs from './components/tabs';


ReactDOM.render(
    <Tabs />
  , document.querySelector('.container'));

and the css

和 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.

这是我想要改进的内容的骨架,因此将 tabNumber 增加到 4 以上会破坏 css。

回答by Vadim Plisko

Here is a code I came Up with:

这是我想出的代码:

import React, {Component} from "react";
import './header.css'

export default class Header extends Component{
    state = {
        active : false
    };


    toggleMenuSwitch = () => {
        this.setState((state)=>{
            return{
                active: !state.active
            }
        })
    };
    render() {
        //destructuring
        const {active} = this.state;

        let className = 'toggle__sidebar';

        if(active){
            className += ' active';
        }

        return(
            <header className="header">
                <div className="header__wrapper">
                    <div className="header__cell header__cell--logo opened">
                        <a href="#" className="logo">
                            <img src="https://www.nrgcrm.olezzek.id.lv/images/logo.svg" alt=""/>
                        </a>
                        <a href="#" className={className}
                           onClick={ this.toggleMenuSwitch }
                           data-toggle="sidebar">
                            <i></i>
                        </a>
                    </div>
                    <div className="header__cell">

                    </div>
                </div>
            </header>
        );
    };
};