【问题标题】:Simplify javascript expression简化 javascript 表达式
【发布时间】:2021-11-28 05:37:11
【问题描述】:

我在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;
};

我想以某种方式简化这似乎对我来说真的很奇怪,但我害怕失去一些案例。有什么帮助吗?

【问题讨论】:

    标签: javascript reactjs function


    【解决方案1】:

    不确定它是否更简单,但您可以尝试以下方法:

    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>
        );
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-27
      • 2016-07-13
      • 2014-09-16
      相关资源
      最近更新 更多