我正在嘗試使用 TypeScript 在功能組件中執行以下操作(我對其進行了一點抽象):
return <IonToast {canClose && button={close}}
不允許將道具包裝在條件中。但是,擁有這種邏輯的最佳解決方案是什么?
我雖然關于在回傳之前分配“關閉”變數,但由于 Ionic 是一個外部組件庫,它不接受空變數。
IonToast 在節點模塊中輸入以下內容。因此,如果您傳遞除有效值之外的任何內容,它不喜歡它。
export interface ToastOptions {
buttons?: (ToastButton | string)[];
}
ts 錯誤是這樣的
Types of property 'button' are incompatible. Type 'string | boolean | undefined' is not assignable to type 'string | undefined'. Type 'false' is not assignable to type 'string | undefined'.
uj5u.com熱心網友回復:
更新
根據這個檔案
您可以為您的buttons屬性設定此邏輯
const buttons: ToastButton[] = canClose ? [close] : [] //`close` needs to be `ToastButton` type
return <IonToast buttons={buttons} />
舊答案
我不知道哪個是這種情況下的最佳解決方案,但我個人使用這種方式
return <IonToast button={canClose ? close : () =>{}} />
第二個引數是一個空函式,有助于防止錯誤,以防萬一你在組件中呼叫button()(間接到close()) 。IonToast
uj5u.com熱心網友回復:
有很多解決方案可以做到這一點。如果您在相同條件下有許多屬性,則可以將它們包裝在一個物件中。由于IonToast期望形狀的道具 - > https://ionicframework.com/docs/api/toast#toastoptions你應該使用buttons而不是button
return <IonToast {...(canClose && {buttons:[close]})}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/457034.html
