首页 > 解决方案 > 在反应jsx中有条件地呈现className

问题描述

var array = [
  ['2','35'],
  ['80','30'],
  ['300','25']
]

所以这是数组的简化版本,我从 api 调用中得到什么。每个子数组的第一个值是数量,第二个值是价格。下面是我的简化状态

this.state = {quantity:''}

在 jsx 内部,我想做的是根据状态的数量值有条件地渲染一个名为selected的类名。每当状态发生变化时。所选课程也应相应更改。下面是我的 jsx

{array.map((price, index, arr) => {
  if (index < arr.length -1) {
      if (parseInt(arr[index+1][0]) > parseInt(this.state.quantity) && parseInt(this.state.quantity) >= parseInt(price[0])){
          return (
            <div className='price-box selected'>
              <h3 className='price'>Tk {price[1]}</h3>
              <p className='quantity'>{price[0]} or more</p>
            </div>
          );
      } else {
          return (
            <div className='price-box'>
              <h3 className='price'>Tk {price[1]}</h3>
              <p className='quantity'>{price[0]} or more</p>
            </div>
          );
      }
  } else {
      if (parseInt(this.state.quantity) >= parseInt(price[0])) {
          return (
            <div className='price-box selected'>
              <h3 className='price'>Tk {price[1]}</h3>
              <p className='quantity'>{price[0]} or more</p>
            </div>
          );
      } else {
          return (
            <div className='price-box'>
              <h3 className='price'>Tk {price[1]}</h3>
              <p className='quantity'>{price[0]} or more</p>
            </div>
          );
      }
  }      
})}

这里一切正常(除了数量 0 和 1 之外,所有条件都按预期评估为 false。所以没有为单个 div 分配选定的类)。我 100% 确定有一种更短更好的方法。

标签: javascriptcssreactjs

解决方案


也许像这样的东西就是你要找的东西?

Codesandbox 上的工作示例

class Quantity extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      quantity: "2"
    };
  }

  render() {
    const array = [["2", "35"], ["80", "30"], ["300", "25"], ["2"], ["", "3"]]; // With some errors
    return (
      <div>
        <h1>Hello</h1>
        {array.map((row) => {
          const condition = this.state.quantity === row[0]; // Create your condition
          if (row && row[0] && row[1])
            return (
              <div className={`price-box ${condition && "selected"}`}> // Called template literal, you can simply include selected if your condition is true
                <h3>Quantity {row[0]}</h3>
                <p>Price {row[1]}</p>
              </div>
            );
          else return <div>Data error</div>;
        })}
      </div>
    );
  }
}

推荐阅读