[英]Can I add multiple variables for the state in React Typescript without changing the interface?
我正在嘗試向反應組件的狀態添加一個變量。 這是組件的外觀:
export class Item extends React.Component<{}, State>{
now: Date;
constructor(props: any) {
super(props);
this.state = {
tab: Tabs.example,
e1: {},
e2: {},
e3: {},
e4: {},
e5: {},
e6: {},
e7: {},
e8: {},
e9: {}
}
this.now = new Date();
}
接口狀態已經定義為
interface State {
tab: Tabs
e1: any
e2: any
e3: any
e4: any
e5: any
e6: any
e7: any
e8: any
e9: any
}
我想將另一個對象foo
添加到我的組件“Item”的狀態,但我無法更改界面。 有沒有辦法在不弄亂界面的情況下將foo: any
添加到狀態變量中?
您可以嘗試擴展接口,以便您可以保持類型安全/嚴格性 - 這有助於開發人員(或至少我)使用 javascript 保持理智並獲得打字稿的好處
interface StateWithFoo extends State{
foo: any
}
export class Item extends React.Component<{}, StateWithFoo>{
如果擴展不是一種選擇,還有其他方法; 您可以嘗試使用 Partial 或其他 TypeScript 功能,每個功能都有一些權衡。
我采用擴展接口方法,因為它保持了類型安全/嚴格性,但如果這不起作用,我們可以討論其他選項
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.