我想检查状态的真值并相应地设置一个类。下面的代码就是这样做的,但是...

有没有办法以编程方式执行此操作,也许可以通过for循环来添加所有内联函数检查。

这样做的原因是,在某些情况下,我有数百个项目,并且我不愿重复并粘贴相同的代码数百次。



class App extends React.Component {
  constructor() {
    super();

    this.state = {
      item1: false,
      item2: true,
      item3: false
    }
  }

  render() {
    return(
      <div className="app">
        <ul>
            <li data-item="item1" className={(this.state.item1) ? "active" : null}>Item 1</li>
            <li data-item="item2" className={(this.state.item2) ? "active" : null}>Item 2</li>
            <li data-item="item3" className={(this.state.item3) ? "active" : null}>Item 3</li>
        </ul>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));

.active {
  color: green;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>

最佳答案

如果有成千上万个,则它们可能应该位于数组而不是对象中。但是,如果需要,我们可以将对象的属性名称作为数组获取。

改用数组(请参见注释):



class App extends React.Component {
  constructor() {
    super();

    // Turning items into an array
    this.state = {
      items: [
        {name: "item1", label: "Item 1", state: false},
        {name: "item2", label: "Item 2", state: true},
        {name: "item3", label: "Item 3", state: false}
      ]
    };
  }

  render() {
    return(
      <div className="app">
        <ul>
          {/* Loop through the items, outputting them*/}
          {this.state.items.map(item => (
            <li data-item={item.name} className={item.state ? "active" : null}>{item.label}</li>
          ))}
        </ul>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));

.active {
  color: green;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>





使用您现有的对象加上另一个对象为我们提供项目标签(请参阅注释):



class App extends React.Component {
  constructor() {
    super();

    this.state = {
      item1: false,
      item2: true,
      item3: false
    };

    // The labels we want on the items
    this.itemNames = {
      item1: "Item 1",
      item2: "Item 2",
      item3: "Item 3"
    };
  }

  render() {
    return(
      <div className="app">
        <ul>
          {/* Loop through the items, outputting them*/}
          {Object.keys(this.state).map(key => (
            <li data-item={key} className={this.state[key] ? "active" : null}>{this.itemNames[key]}</li>
          ))}
        </ul>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));

.active {
  color: green;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>

09-25 16:28