简体   繁体   English

使用三元嵌套 If Els 语句 React 渲染 className

[英]Render className with ternary nested If Els statement React

I do have a small issue I do need to render a className based on few conditions.我确实有一个小问题,我确实需要根据几个条件呈现 className。 I have a Play button, Live button and general buttons.我有一个播放按钮、实时按钮和通用按钮。 Most classes are the same, but I do need to add extra class to a play button.大多数类都是相同的,但我确实需要向播放按钮添加额外的类。

My code so far is looking like this:到目前为止,我的代码如下所示:

 className={`"Controller-Button player-btn icon" ${
          isSelected
            ? `${btnName === "PLAYER_LIVE" ? " live-button" : ""}`
            : `${btnName === "PLAYER_LIVE" ? " live-button" : ""}`
        }`}

And now I am stuck.现在我被困住了。 I need to add extra condition before isSelecetd: btnName === "PLAYER_PLAY" ? " play-button" : ""我需要在 isSelecetd 之前添加额外的条件: btnName === "PLAYER_PLAY" ? " play-button" : "" btnName === "PLAYER_PLAY" ? " play-button" : "" but i do have issue how properly put this in such render. btnName === "PLAYER_PLAY" ? " play-button" : ""但我确实有问题如何正确地将其放入这种渲染中。 If I will add btnName === "PLAYER_LIVE" ? " live-button" : "play-button"如果我要添加btnName === "PLAYER_LIVE" ? " live-button" : "play-button" btnName === "PLAYER_LIVE" ? " live-button" : "play-button" this class wil be in all buttons. btnName === "PLAYER_LIVE" ? " live-button" : "play-button"这个类将在所有按钮中。

You can use something like that:你可以使用这样的东西:

const classes = ["Controller-Button", "player-btn", "icon"];
if(isSelected) {
  classes.push("live-button")
} else if(somethingCondition) {
   classes.push("someClass")
}

etc...等等...

 className={classes.join(' ')}

I would suggest to move this logic into a function.我建议将这个逻辑移到一个函数中。 Something like就像是

const getClassName = () => {
  let className
  if (btnName === 'PLAYER_PLAY') {
    // applicable logic here for className here
  } else {
    // applicable logic here for className here
  }
  return className
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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