响应条件渲染,返回渲染中的数组,反应16

时间:2017-11-07 07:38:14

标签: javascript reactjs

我想在render函数中返回一个数组元素。 如果我使用:

 <div> 

就像容器运行良好一样,如果我删除了条件行,它就像这样工作:

{ 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}
      />
    ];

我做错了什么?

1 个答案:

答案 0 :(得分:1)

删除条件周围的{},它会起作用。需要{}将js表达式放在JSX中,如果你在其他地方使用它,那么这意味着你试图返回对象

像这样写:

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}
    />
];