Add class when button is clicked in response.js file

I have been working on React for several weeks, and while I have the basic syntax down (props, states), I am struggling to draw some links with some concepts, especially with the addition of classes when the state changes. I'm trying to build simon says a game that contains four buttons, all built using the Button component. Initially, they have opacity .3 and the active state is false. When pressed, the “active” state becomes true, but I can’t understand for life how to add a css class that can give the button full opacity. Here is my code:

class App extends Component {
  constructor(){
    super();
    this.state = {
      active: false
    }
  }
  handleClick(){
    this.setState({active: !this.state.active})
  }
  renderButtons(i, f){
    return <Button value={i} className="button" id={f} active= {this.state.active} onClick={() => this.handleClick()}/>
  }
  render() {
    return (
      <div className="App">
        {this.renderButtons("red", "buttonRed")}
        {this.renderButtons("blue", "buttonBlue")}
        {this.renderButtons("green", "buttonGreen")}
        {this.renderButtons("yellow", "buttonYellow")}
      </div>
    );
  }
}

And my css:

.button{
  width: 100px;
  height: 45px;
  opacity: .3;
  margin: 0 auto;
  margin-bottom: 30px;
}
#buttonRed{
  background: red;
}
#buttonBlue{
  background: blue;
}
#buttonGreen{
  background: green;
}
#buttonYellow{
  background: yellow;
}

, , "button". - ?

+4
3

React . , . - className an Object string. , , , classnames. npm install --save classnames yarn add classnames. :

import classNames from 'classnames';

:

<button className={classNames({button: true, active: this.state.active})} />

, , - JavaScript . , classNames(). , :

render(){
    const classes = classNames({
        button: true, // we always want this class
        active: this.state.active, // only add this class if the state says so
     });

     return (
          <button className={classes} />
     );
}
+7

className="button" className={'button ' + f}

, , javascript

, "" .

JSX , React HTML-, class="button red".

0

, renderButtons, :

...
 renderButtons(i, f, c){
    var cssClass =  c&&c!=""? "button " + c : "button";   
    return <Button value={i} className={cssClass}  id={f} active= {this.state.active} onClick={() => this.handleClick()}/>
  }
...
0

Source: https://habr.com/ru/post/1671095/


All Articles