React & clsx:如果映射数组中的当前项目是多个项目中的第一个,则添加 class 名称

React & clsx: add a class name if the current item in a mapped array is the first of multiple items

我有以下代码,我需要向其中添加一些新功能。基本上,map 函数是遍历数组,如果数组中只有一个项目,那么我不想添加新的 class,但如果这是 2 的数组中的第一项项,我想添加一个 class 名称。

                            {section?.values?.link.map((link, index) => {
                              return (
                                <LinkComponent
                                  key={index}
                                  className={clsx({
                                    "jc-left":
                                      link?.values?.linkType !== 
                                      "primary-button",
                                  })}
                                </LinkComponent>
                              ...

我知道它看起来像已经存在的那个,因为我将 class 名称放在引号中,后跟分号,然后是规则,我只是不知道怎么写对我来说就像一个复杂的规则。感谢任何帮助。

如果我正确理解你的问题是你想添加 className 如果你 array.length > 1 然后添加 class 到数组的第一项。

{section?.values?.link.map((link, index, self) => {
return (
    <LinkComponent
          key={index}
          className={clsx({
            "jc-left": link?.values?.linkType !== "primary-button",
             "YOUR_CLASS": self.length > 1 && index === 0,
          })}
    </LinkComponent>

但是,如果您有两个以上的项目怎么办,那么我假设您将 class 添加到除最后一个项目之外的所有项目中

{section?.values?.link.map((link, index, self) => {
return (
    <LinkComponent
          key={index}
          className={clsx({
            "jc-left": link?.values?.linkType !== "primary-button",
             "YOUR_CLASS": self.length > 1 && (index + 1 !== self.length),
          })}
    </LinkComponent>

如果您想使用 clsx 有条件地渲染,您可以根据以下两个条件执行此操作:

{section?.values?.link.map((link, index) => {
  // Checks if array has more than 2 or 2 items and if the index is 0 which means that is the first item.
  const hasConditionalClass = section?.values?.link.length >= 2 && index === 0;

  return (
    <LinkComponent
      key={index}
      className={clsx({
       "jc-left": link?.values?.linkType !== "primary-button",
       "condtional-class": hasConditionalClass
       })}
    </LinkComponent>
    ...