簡體   English   中英

如何將類型聯合道具擴展到反應 class 組件?

[英]How to extend type union props to a react class component?

我有兩個道具showAccountNameaccountType 只有當accountType為 true 時才需要showAccountName 當 showAccountName 為 false 時,不需要 accountType。

所以,我使用了類型聯合 -

type AccountProps = 
| { showAccountName?: false; accountType: never; }
| { showAccountName?: true; accountType: string; }

並嘗試在 class 組件中擴展這些道具

class UserAccount extends React.PureComponent<AccountProps> 
{ .... }

但我無法在 UserAccount 中使用this.props訪問 showAccountName 或 accountType。 知道我在這里做錯了什么嗎? 或者有沒有其他方法可以根據另一個可選道具強制使用一個道具? (不使用類型)我是 typescript 的新手,非常感謝任何幫助!

與其在這兩種情況下都將showAccountName可選道具,不如僅在它應該是虛假的情況下使其可選(並且在這種情況下也只需省略另一個道具):

{ showAccountName?: false; }

並且在您希望顯示它的情況下,使兩個道具都不是可選的:

{ showAccountName: true; accountType: string; }

所以,在一起,它看起來像這樣:

import {default as React} from 'react';

type AccountProps = 
  | { showAccountName?: false; }
  | { showAccountName: true; accountType: string; };

class UserAccount extends React.PureComponent<AccountProps> {
  render () {
    return (
      <div>
        {this.props.showAccountName ? this.props.accountType : 'Account type not shown'}
      </div>
    );
  }
}

TS游樂場

暫無
暫無

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

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