REACT - 切换课程onclick [英] REACT - toggle class onclick

查看:93
本文介绍了REACT - 切换课程onclick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何切换活动类 onClick 来更改CSS属性。

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

I采取了很多方法,并阅读了许多SO答案。使用jquery它会相对简单,但是,我无法通过反应来解决这个问题。我的代码如下。任何人都可以建议我该怎么做?

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?

如果没有为每个项目创建新组件,是否可以这样做?

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>
  }

}


推荐答案

使用状态。 Reacts文档是此处

Use state. Reacts docs are here.

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>
        );
    }
}

这篇关于REACT - 切换课程onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆