如果是扩展运算符中的else语句

时间:2017-06-28 12:59:36

标签: reactjs

我对React很新,并且在尝试添加" if"时遇到了一些麻烦。传播组件中的陈述:

示例代码:

class CalenderView extends Component {
  parseActivitiesForCalendar = (activities) => {
    return activities.map((activity) => {
      return {
        ...activity,
        id: activity.id,
        title: Dates.getTimeString(activity.startDate) +" - "+ activity.desc,
        start: Dates.getDateTimeFromUnix(activity.startDate),
        end: Dates.getDateTimeFromUnix(activity.endDate)
      }
    })
  }

使用"标题",我正在尝试添加以下条件:

if(Dates.getTimeString(activity.startDate)=="00:00") {
    title: "All Day - "+ activity.desc,
} else {
  title: Dates.getTimeString(activity.startDate) +" - "+ activity.desc,
}

但不确定如何写这个。有什么想法吗?

3 个答案:

答案 0 :(得分:2)

使用ternary operator

这样写
return {
    ...activity,
    id: activity.id,

    title: Dates.getTimeString(activity.startDate) == "00:00" ? "All Day - " + activity.desc : Dates.getTimeString(activity.startDate) +" - "+ activity.desc,

    start: Dates.getDateTimeFromUnix(activity.startDate),
    end: Dates.getDateTimeFromUnix(activity.endDate)
}

答案 1 :(得分:2)

如果在对象中不起作用,您可以使用三元运算符来获得所需的结果。

class CalenderView extends Component {
  parseActivitiesForCalendar = (activities) => {
    return activities.map((activity) => {
      return {
        ...activity,
        id: activity.id,
        title: (Dates.getTimeString(activity.startDate)=="00:00")? "All Day - "+ activity.desc : Dates.getTimeString(activity.startDate) +" - "+ activity.desc,
        start: Dates.getDateTimeFromUnix(activity.startDate),
        end: Dates.getDateTimeFromUnix(activity.endDate)
      }
    })
  }

答案 2 :(得分:1)

这应该有所帮助。

title: Dates.getTimeString(activity.startDate)=="00:00"? "All Day - "+ activity.desc : Dates.getTimeString(activity.startDate) +" - "+ activity.desc;