简体   繁体   中英

Conditionals in React

How do I use conditionals in React?

Essentially, for customerClassesRemaining, I currently say "class(es)" but I want to write code that says if there's one class, use "class," and if there's more than one class, use "classes." Thanks!

render() {
    const loadBoxes = (
      Array.from({ length: 20 }).map((n, i) => (
        <LoadBox key={`${i}${n - 1}key`} />
      ))
    );
    const customerBoxes = !this.props.customersLessThanFive ? loadBoxes
    : this.props.customersLessThanFive.map((customer, i) => (

      if (customer.classes_remaining == 1) {
        customerClassesRemaining2 = {`${customer.classes_remaining} class left`}
      }
      else {
        customerClassesRemaining2 = {`${customer.classes_remaining} classes left`}
      }


      <CustomerFewerFiveBox
        key={customer.id}
        customerIndex={i + 1}
        customerName={`${customer.firstName} ${customer.lastName}`}
        customerClassesRemaining={`${customer.classes_remaining} class(es) left`}
        customerPackage = {customer.name}
        customerExpiration = {`Expiration: ${customer.expiration_date}`}
        
      />
    ))

你可以试试,

customerClassesRemaining2 = customer.classes_remaining == 1 ? `${customer.classes_remaining} class left` : `${customer.classes_remaining} classes left`;

使用三元运算符,例如:

customerClassesRemaining={`${customer.classes_remaining} class${customer.classes_remaining > 1 ? 'es' : ''} left`}

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