How to instantiate react component with injected properties

随声附和 提交于 2019-12-02 05:58:58

There are a lot of problems around the mobx inject method.

the original idea was to return a Partial<TProps> but you can't do this typed without losing your original Class: React.Component<Partial<TProps>,TState> != YourComponent - the set properties.

Read the discussed problem here: https://github.com/mobxjs/mobx-react/issues/256

Simplistic solution

Use optional parameters in props and set them in a getter property:

interface AppProps {
    store?: SDtore;
}

class App {
  get store(): TimeEntryStore {
    return this.props.store as Store;
  }
  method(){
     this.store;///
  }
}

Other solution

If you want to keep your required parameters (eg: for using the component outside of mobx etc).

You can consider casting the component to React.Component<TPropsReduced,State> where TPropsReduced is a self defined interface with required props after injected.

The downsides are:

  • Losing type safety at casting (eg if you make mistakes/typo's in the interface properties. (can be solved by extending/subclassing interfaces.
  • Losing methods calls. You will no longer have typed methods on the component (eg: when you use ref={()=>}), but using this is dis-advised anyways.

Example:

interface AddressPropsMobx {
}

interface AddressProps extends AddressPropsMobx {
  report: IReportStore;
}



//Pure react component
class Address extends React.Component<AddressProps> {}

// Mobx version:
const MobxAddress = inject((rootStore: RootStore) => ({
  report: rootStore.report
}))(observer(Address)) as React.Component<AddressPropsMobx>;  //unsafe cast
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!