简体   繁体   中英

React.js | How to handle className in a better way?

I want to handle className using event and state, like this

class SampleComponent extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      class1: 'bar',
      class2: 'bar'
    };
  }

  handleBarClick() {
    this.setState({
      class1: 'bar active',
      class2: 'bar'
    });
  }

  handleFooClick() {
    this.setState({
      class1: 'bar',
      class2: 'bar active'
    });
  }

  render() {
    return (
      <div>
        <span className={this.class1} onClick={this.handleBarClick.bind(this)}>bar</span>
        <span className={this.class2} onClick={this.handleFooClick.bind(this)}>foo</span>
      </div>
    );
  }
}

but this code is kind of wasteful, it should be more briefly.

I want to write in a better way, can anyone give some advice? Thanks.

You can use classNames ( https://github.com/JedWatson/classnames ) to achieve the same in a better way, something like this:

first import className:

import className from 'classnames'

second get the classes from your state:

<span className={ className('bar', {'active': this.state.active, 'otherClass': this.state.booleanValue }) } />

this will end like this if you have true in active and booleanValue:

<span class='bar active otherClass'  />

or like this if is false

<span class='bar'  />

Try this:

class SampleComponent extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      itemName='bar'
    };
  }

  handleItemClick(itemName) {
    this.setState({itemName:itemName});
  }

  render() {
    return (
      <div>
        <span className={this.state.itemName == 'bar' ? 'bar active' : 'bar'} onClick={this.handleItemClick.bind(this, 'bar')}>bar</span>
        <span className={this.state.itemName == 'foo' ? 'bar active' : 'bar'} onClick={this.handleItemClick.bind(this, 'foo')}>foo</span>
      </div>
    );
  }
}

This is slightly cleaner

class SampleComponent extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      activeBar: 0
    };
  }

  handleBarClick(number) {
    this.setState({
      activeBar: number
    });
  }

  render() {
    var class1 = this.state.activeBar == 1 ? "bar active" : "bar";
    var class2 = this.state.activeBar == 2 ? "bar active" : "bar";

    return (
      <div>
        <span className={class1} onClick={this.handleBarClick.bind(this, 1))}>bar</span>
        <span className={class2} onClick={this.handleBarClick.bind(this, 2)}>foo</span>
      </div>
    );
  }
}

I would do it like this:

class SampleComponent extends React.Component {

  state = {
    activeIndex: 0
  };

  handleClick(index) {
    this.setState({ activeIndex: index });
  }

  render() {
    const { activeIndex } = this.state;

    return (
      <div>
        {
          ['bar', 'foo'].map((item, index) => (
            <span
              className={`bar${activeIndex === index ? ' active' : ''}`}
              onClick={() => this.handleClick(index)}
              key={index}
            >
              {item}
            </span>
          ))
        }
      </div>
    );
  }
}

See demo fiddle: https://jsfiddle.net/free_soul/6snyL2rc/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM