簡體   English   中英

如何有條件地將道具傳遞給 React JS 中的組件

[英]How to pass props conditionally to a component in React JS

我有一個名為“Switch”的組件,它需要一些參數,例如 label、name、onChange、selected 等。

現在,在我的場景中,我正在調用 API 並獲得響應。 在 JSON 響應中,我的字段值為“是”或“否”。

如果值為“是”,我需要將“已切換”傳遞給組件,否則不傳遞任何內容。

          <Switch
            label={field.label}
            name={field.fieldID}
            disabled={field.disabled}
            onChange={this.getNextFields}
            checked
          >
            {field.control.modes[0].options.map((option, index) => {
              return (
                
                  <Strong>{option.key}</Strong>
                
              );
            })}
          </Switch>

我如何通過它? 我正在嘗試使用三元運算符。 但沒有運氣。 您的幫助將不勝感激。

您可以在道具定義中使用三元運算符。

<Switch
  label={field.label}
  name={field.fieldID}
  disabled={field.disabled}
  onChange={this.getNextFields}
  checked={{ Yes: true, No: false }[field.value]}
>
  {field.control.modes[0].options.map((option, index) => {
    return <Strong>{option.key}</Strong>;
  })}
</Switch>

你可以試試這樣的 -

<Switch
  label={field.label}
  name={field.fieldID}
  disabled={field.disabled}
  onChange={this.getNextFields}
  checked={field.value === 'Yes' ? 'switched' : ''}
>
  {field.control.modes[0].options.map((option, index) => {
    return (               
      <Strong>{option.key}</Strong>
                    
    );
  })}
</Switch>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM