REACT - toggle class onclick

后端 未结 14 1914
长情又很酷
长情又很酷 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

    A good sample would help to understand things better:

    HTML

    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(
            
    {this.state.addClass ? "Remove a class" : "Add a class (click the box)"}
    Read the tutorial here.
    ); } } ReactDOM.render(, document.getElementById("root"));

提交回复
热议问题