Javascript 如何简化React中的覆盖道具?

Javascript 如何简化React中的覆盖道具?,javascript,reactjs,Javascript,Reactjs,我有一个If语句,并根据状态返回带有额外道具的相同组件。你知道怎么简化吗?我可以使用递归吗?有什么想法吗 iconRight是唯一的区别 renderInput = () => { if (isLoading) { return ( <Input iconRight={( <Spinner /> )} autoComplete="off&q

我有一个If语句,并根据状态返回带有额外道具的相同组件。你知道怎么简化吗?我可以使用递归吗?有什么想法吗

iconRight是唯一的区别

renderInput = () => {
    if (isLoading) {
      return (
        <Input
          iconRight={(
              <Spinner />
          )}
          autoComplete="off"
          id="unique-id-2"
          aria-autocomplete="both"
        />
      );
    }
    return (
      <Input
        autoComplete="off"
        id="unique-id-2"
        aria-autocomplete="both"
      />
    );
  }
}

您可以将道具散布到组件上:

renderInput = () => {
    const props = {
        autoComplete: 'off',
        id: 'unique-id-2',
        'aria-autocomplete': 'off'
    };
    if (isLoading) {
      return (
        <Input
          iconRight={(
              <Spinner />
          )}
          {...props}
        />
      );
    }
    return (
      <Input {...props} />
    );
  }
}

但我建议更改您的输入组件以接受加载道具,并让输入组件处理该逻辑。它还将使您的消费代码更易于阅读。

我认为您的功能可以缩短为以下内容:

renderInput = () => (
    <Input
        iconRight={isLoading ? (<Spinner />) :  null}
        autoComplete="off"
        id="unique-id-2"
        aria-autocomplete="both"
    />
)
如果还没有,请在输入组件中检查iconRight道具是否为空,然后仅渲染它。

您可以尝试以下操作:

renderInput = () =>(
        <Input
          iconRight={
           isLoading && (
              <Spinner />
          )}
          autoComplete="off"
          id="unique-id-2"
          aria-autocomplete="both"
        />
    )