簡體   English   中英

如何根據條件選擇 React 組件道具

[英]How to chose a React component props depending on condition

我有以下 React 組件:

<SweetAlert 
    show={this.props.message} 
    success 
    title={this.props.message}
    onConfirm={this.props.handleCloseAlert}>
</SweetAlert>

這是我收到的警報:

在此處輸入圖片說明

但是我希望在執行時動態選擇 props success ,所以我嘗試了這個:

 const alertType = () => {
    switch(this.props.type) {
        case ALERT_ERROR:
          return 'error'
        case ALERT_WARNING:
          return 'warning'
        case ALERT_DANGER:
          return 'danger'
        case ALERT_INFO:
          return 'info'
        case ALERT_SUCCESS:
          return 'success'
      }
    }

<SweetAlert 
    show={this.props.message} 
    {...alertType()}
    title={this.props.message}
    onConfirm={this.props.handleCloseAlert}>
</SweetAlert>

但我失去了警報類型:

在此處輸入圖片說明

我還沒有找到向組件添加任意道具的方法。

您應該將type作為函數的返回值傳遞

<SweetAlert 
    show={this.props.message} 
    type={alertType()}
    title={this.props.message}
    onConfirm={this.props.handleCloseAlert}>
</SweetAlert>

來源為何傳球的success作為一個布爾工作

如果你為組件返回一個對象,比如{danger: true}

switch(this.props.type) {
        case ALERT_ERROR:
          return {error: true}
        case ALERT_WARNING:
          return {warning: true}
        case ALERT_DANGER:
          return {danger: true}
        case ALERT_INFO:
          return {info: true}
        case ALERT_SUCCESS:
          return {success: true}
      }
    }

寫作

<MyComponent myProp/>

只是一個簡寫符號

<MyComponent myProp={true}/>

因此,將return 'error'更改為return {error: true}應該對您有用

暫無
暫無

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

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