对条件渲染做出反应,对渲染中的 return 数组作出反应,反应 16

reacts conditional rendering, to return array in render, react 16

我想 return 在 return 函数内渲染数组元素。 如果我使用:

 <div> 

like 容器运行良好,它最初是这样运行的,如果我删除条件行:

{ index === 0 && subindex===0 &&
}

效果也很好:

我在有条件的前一行得到错误:

Syntax error: Unexpected token, expected

这里是我的代码:

    return [
      { index === 0 && subindex===0 &&
        <a href="#" onClick={() => fields.remove(subindex)}>
          <ShowIcon size="25" color="darkred" icon="removecircleblack"/>
        </a>,
      }

      <Field
        key={fieldKey}
        name={`${rowValues}.${fieldKey}`}
        type={subfield.typeInput ? subfield.typeInput : 'text'}
        typeInput={subfield.typeInput ? subfield.typeInput : 'text'}
        component={FormField}
        placeHolder={subfield.placeHolder ? t(`form.${fieldParentKey}-${fieldKey}`) : ''}
        listSource={subfield.listSource ? aSources[subfield.listSource] : ''}
        index={subindex + 1}
        width="270px"
        icon={subfield.icon}
      />
    ];

我做错了什么?

去掉条件周围的{},就可以了。 {} 需要将 js 表达式放在 JSX 中,如果您在其他地方使用它,则意味着您正在尝试 return 一个 Object.

这样写:

return [
    index === 0 && subindex===0 ?
      <a href="#" onClick={() => fields.remove(subindex)}>
        <ShowIcon size="25" color="darkred" icon="removecircleblack"/>
      </a>
      :null,

    <Field
      key={fieldKey}
      name={`${rowValues}.${fieldKey}`}
      type={subfield.typeInput ? subfield.typeInput : 'text'}
      typeInput={subfield.typeInput ? subfield.typeInput : 'text'}
      component={FormField}
      placeHolder={subfield.placeHolder ? t(`form.${fieldParentKey}-${fieldKey}`) : ''}
      listSource={subfield.listSource ? aSources[subfield.listSource] : ''}
      index={subindex + 1}
      width="270px"
      icon={subfield.icon}
    />
];