簡體   English   中英

React typescript 將 props 接口傳遞給 class 組件

[英]React typescript pass props interface to the class component

我有組件:

interface IComponentAProps {
  sameData: string;
  data: IDataA;
  callback: (data: IDataA) => void;
}

class ComponentA extends Component<IComponentAProps> {
  render() {
  // ...
  }
}

// and in other component:

render() 
  return (<ComponentA callback={...} sameData={...} data={data} />);
}

如何將 IComponentAProps 傳遞給 ComponentA? 使用它更通用? 我不想創建另一個組件來執行此操作:

interface IComponentBProps {
  sameData: string;
  data: IDataB;
  callback: (data: IDataB) => void;
}

class ComponentB extends Component<IComponentBProps> {
  render() {
  // ...
  }
}

// and in other component:

render() 
  return (<ComponentB callback={...} sameData={...} data={data} />);
}

我可以做這樣的事情嗎?

class ComponentA<T> extends Component<T & IComponentAProps> 

interface INewInterface {
  data: INewData;
  callback: (data: INewData) => void;
}

// and in other component:

render() 
  return (<ComponentA<INewInterface> callback={...} sameData={...} data={data} />);
}

做這個的最好方式是什么?

如果您將此接口添加到您的interfaces.d.ts中,它將可以通過整個應用程序訪問。

但是在這種情況下,我認為最好將接口導出到ComponentA中並導入到ComponentB中。

您可以創建通用接口並在組件中擴展它:

// file with common types
export interface IComponentCommonProps {
  sameData: string;
}

//file with component A
import {IComponentCommonProps} from 'FILE_WITH_COMMON_TYPES';

interface IComponentAProps extends IComponentCommonProps {
  data: INewData;
  callback: (data: INewData) => void;
}

class ComponentA extends Component<IComponentAProps> {
  render() {
  // ...
  }
}



//file with component B
import {IComponentCommonProps} from 'FILE_WITH_COMMON_TYPES';

interface IComponentBProps extends IComponentCommonProps {
  data: INewData;
  callback: (data: INewData) => void;
}

class ComponentB extends Component<IComponentAProps> {
  render() {
  // ...
  }
}

// another component
render() 
  return (
    <div>
      <ComponentA callback={...} sameData={...} data={data} />
      <ComponentB callback={...} sameData={...} data={data} />
    </div>
  );
}

根據您寫的內容,我假設您希望兩個組件共享一個相似的界面。

兩個組件共享相同的藍圖——只是data的形狀不同。 這是通用道具的一個很好的用例。

interface Props<T> {
  sameData: string;
  data: T;
  callback: (data: T) => void;
}

declare class MyComponent<T> extends Component<Props<T>> {}

這樣的組件現在可以與任何data一起使用。

const user = {
  name: 'Bob',
};

<MyComponent<typeof user>
  data={user}
  sameData="potato"
  callback={data => console.log(data.name)}
/>;

const animal = {
  species: 'dog',
};

<MyComponent<typeof animal>
  data={animal}
  sameData="potato"
  callback={data => console.log(data.species)}
/>;

暫無
暫無

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

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