如何从继承的类覆盖React.Component状态类型?

时间:2019-08-08 21:28:20

标签: reactjs typescript generics overwrite

我有一个扩展另一个组件的组件类,我试图弄清楚如何覆盖我继承自的状态的类型。

这是一个例子:

class MyComponent extends React.Component<SomeProps, SomeState> {
  // ...
}

class ExtendedComponent extends MyComponent {
  // How to overwrite SomeState?
  // This component needs to store a different model of state.
}

我需要ExtendedComponent为其interface使用不同的state,但是我不太想知道如何实现。


编辑:现在到某处!

但是,现在Parent充满了与状态修改有关的各种错误。这是到目前为止我得到的:

interface ParentProps {
  a: string;
}

interface ParentState {
  b: string;
}

class Parent<P, S> extends React.Component<ParentProps & P, ParentState & S> {
  constructor(props) {
    super(props);

    // Type '{ b: "hello"; }' is not assignable to type 'Readonly<ParentState & S>'
    this.state = {
      b: 'hello',
    };
  }

  aFunction(): void {
    /*
      Argument of type '{ b: "testing"; }' is not assignable to parameter of type '(ParentState & S) | ((prevState: Readonly<ParentState & S>, props: Readonly<ParentProps & P>) => (ParentState & S) | Pick<ParentState & S, "b">) | Pick<ParentState & S, "b">'.
  Type '{ b: "testing"; }' is not assignable to type 'Pick<ParentState & S, "b">'.
    Types of property 'b' are incompatible.
      Type '"testing"' is not assignable to type 'string & S["b"]'.
        Type '"testing"' is not assignable to type 'S["b"]'.
    */
    this.setState({
      b: 'testing',
    });
  }
}

interface ChildProps {
  c: string;
}

interface ChildState {
  d: string;
}

class Child extends Parent<ChildProps, ChildState> {
  constructor(props) {
    super(props);

    // This is what I'm after -- and TypeScript doesn't complain :)
    this.state = {
      b: 'hello',
      d: 'world',
    };
  }
}

1 个答案:

答案 0 :(得分:3)

我猜您不想替换道具和状态,因为您可能需要一个通用接口来使父类起作用。因此,您可以使您的父类通用,然后合并其他道具/状态。

purchasedItems = new List<BrandsTransactionItem>();

foreach (var query in purchaseQuery)
{
BrandsTransactionItem tempItem;
tempItem = purchasedItems.Where(e => e.day == query.day).Where(e => e.brandName == query.brandName).FirstOrDefault();

//If item not in list already, 
if (tempItem == null)
{
   purchasedItems.Add(new BrandsTransactionItem()
   {
    brandName = query.brandName,
    day = query.day,
    totalPurchased = query.TotalPurchased,
    costOfItem = query.costOfItem
   });
}
// if it already exists, just add to amount purchased
else
{
  tempItem.totalPurchased += query.totalPurchased;
}
}

foreach (var item in purchasedItems)
{
  double dailyProfit = (double)(item.totalPurchased * item.costOfItem);
  dailyProfit = Math.Round(dailyProfit, 2); // make it decimal of 2

  // Items is the list that I want to display in MVC
  Items.Add(new BrandsProfit(){
  brandName = item.brandName,
  day = item.day,
  totalDailyProfit = dailyProfit
  });
}

使用示例:

class MyComponent<P, S> extends React.Component<ParentProps & P, ParentState & S> {}
//                ^ Generic P is for child props, Generic S is for child state