Shorthand if/else 缺少结束标记导致语句错误

Shorthand if/else statement error from missing closing tag

当我使用 {props.dollarsInputGroup ? <InputGroup><InputGroup.Addon>$</InputGroup.Addon> : ''} 时,该语句不起作用,因为 <InputGroup> 没有结束标记。我在这里错过了什么?

更新

<FormGroup>
  {props.dollarsInputGroup ? <InputGroup><InputGroup.Addon>$</InputGroup.Addon> : ''}
  <Input />
  {props.dollarsInputGroup ? </InputGroup> : ''}
  {props.error ? <HelpBlock>{props.error}</HelpBlock> : '' }
</FormGroup>

您需要重复 <FormControl />,或者将其定义为变量一次并使用它两次(可能与函数一起使用)。例如:

var formControl = <FormControl />;
return <FormGroup>
    {props.dollarsInputGroup ? <InputGroup><InputGroup.Addon>$</InputGroup.Addon>{formControl}</InputGroup> : formControl}
    {props.error ? <HelpBlock>{props.error}</HelpBlock> : null}
</FormGroup>;

或者……(虽然我认为这可读性差很多)

<FormGroup>
    {(props.dollarsInputGroup ? ((fc) => <InputGroup><InputGroup.Addon>$</InputGroup.Addon>{fc}</InputGroup>) : ((fc) => fc))(<FormControl />)}
    {props.error ? <HelpBlock>{props.error}</HelpBlock> : null}
</FormGroup>

虽然您可以在其他地方使用定义来帮助它:

function maybeWrapWithDollars(wrapWithDollars, wrappedControl) {
    if(wrapWithDollars) {
        return <InputGroup><InputGroup.Addon>$</InputGroup.Addon>{wrappedControl}</InputGroup>;
    }else{
        return wrappedControl;
    }
}
// …
<FormGroup>
    {maybeWrapWithDollars(props.dollarsInputGroup, <FormControl />)}
    {props.error ? <HelpBlock>{props.error}</HelpBlock> : null}
</FormGroup>

合并条件:

<FormGroup>
  {props.dollarsInputGroup ? <InputGroup><InputGroup.Addon>$</InputGroup.Addon><Input /></InputGroup> : <Input />}
  {props.error ? <HelpBlock>{props.error}</HelpBlock> : '' }
</FormGroup>