简体   繁体   中英

Simplify javascript expression

i have this function in javascript:

export const commonRenderer = (option, useFormatter, hasSubLabel) => {
  if (useFormatter && hasSubLabel) {
    return (
      <React.Fragment>
        <FormattedMessage id={option.label} /><br /><FormattedMessage id={option.subLabel} />
      </React.Fragment>
    );
  }
  if (!useFormatter && hasSubLabel) {
    return (
      <React.Fragment>
        {option.label}<br />{option.subLabel}
      </React.Fragment>
    );
  }
  if (useFormatter && !hasSubLabel) {
    return (
      <FormattedMessage id={option.label} />
    );
  }
  return option.label;
};

and somehow i want to simplify this seems it looks really odd to me but im afraid of losing some cases. Any help?

Not sure if it's simpler or not, but you may try something like this:

export const commonRenderer = (option, useFormatter, hasSubLabel) => {
    const Element = useFormatter ? FormattedMessage : React.Fragment;
    const attr = useFormatter ? 'id' : 'children';

    return (
        <React.Fragment>
            <Element {...{ [attr]: option.label }} />
            {hasSubLabel && (
                <React.Fragment>
                    <br />
                    <Element {...{ [attr]: option.subLabel }} />
                </React.Fragment>
            )}
        </React.Fragment>
    );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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