react + typescript,如何区分导出和内部道具?

时间:2017-05-19 11:43:45

标签: reactjs typescript mobx react-intl

考虑以下组件:

interface OProps {
  // property here should be sent by parent
  id: string;
}

interface IProps {
  // property here just use internal for intellisense
  notNeed: number;
}

export class Foo extends React.Component<OProps & IProps, void> {}

export class Bar extends React.Component<OProps & InejctedIntlProps, void> {}

当我使用Foo组件时,它应该发送OProps和IProps ......

// error: 'notNeed' is missing
const f = <Foo id="test" />;

// error: 'intl' is missing
const b = <Bar id="test" />;

IProps可能在injectedIntlProps,特别注入道具,mobx商店道具或任何不需要父母注入的道具。

我知道有一些方法可以解决它,例如:

export default injectedIntlProps<OProps>(我不喜欢导出默认值...)或将道具声明为部分notNeed?: number,但仍然想知道是否有更好的解决方案?只出口需要的道具......

1 个答案:

答案 0 :(得分:1)

如果我已经正确理解你在某个父组件中使用了连接/容器组件,并希望区分映射道具(来自redux商店的道具)和自己的道具(从父组件传入的道具) )。

通过将属性拆分为单独的界面,您处于正确的轨道上,您只需要指定哪些道具被映射以及哪些道具是连接函数中自己的道具。

以下是如何为foo组件执行此操作的示例。请注意,您已经省略了组件的很多关键部分,因此我不得不做出一些假设。

import * as React from 'react';

interface IProps {
  id: string;
}

interface IState {
  notNeed: number;
}

export class Foo extends React.Component<IProps, IState> {}

如果我错过了标记并且您没有使用连接组件,那么您只需要使用组件内部状态。

e.g。

state: :sent