如何从装饰器函数获取组件自己的道具

问题描述

我的组件需要使用创建组件时要传递的属性(OwnProps),此外,它还需要使用MobX Store中的道具。我知道如何连接仅使用Mobx Store或仅使用OwnProps的组件。但我找不到同时兼顾两者的方法。这是我写的一个例子。请帮帮我。

// Main App.tsx inside Router
// Properties I passed here I'll call own props.
<Container
    {...match.params}
    id={match.id}
/>

// Container.tsx. Container logic and types are here.
// Own props

import { observer,inject } from 'mobx-react'

export interface ContainerOwnProps {
  id: number,}

// Own props with connected MobX store
type ContainerProps = ContainerOwnProps & {
  store: ContainerStore
}

// In this decorator,I want to inject my MobX store and save my types.
// And this is doesn't work,cause I don't kNow how to pass ownProps argument when I export it below
const connector = (Component: React.FC<ContainerProps>,ownProps: ContainerOwnProps) =>
  inject((state: Stores) : ContainerProps => { // in Stores object I desided to place all my components stores
    return {
      ...ownProps,store: state.ContainerStore
    }
  })(observer(Component));
  
// Main react component. Which uses Own props and props from store
const Container: React.FC<ContainerProps> = 
  (props: ContainerProps) => {
    return (     
       <p id={props.id}>props.store.text</p>
    );
  }

// [Error] It would be nice to kNow how to put "ownProps" here
export default connector(Container,ownProps) 
  
  

解决方法

因此,我进行了一些研究。我发现“注入”模式已经过时。我最终使用带有钩子的“ mobx-react-lite”并对上下文进行响应。这很容易,并且可以响应最佳实践。另外,您可以编写自己的钩子来连接商店。代码看起来像这样:

const storeContext = createContext(mobxStore)    
const useStore = () => useContext(storeContext)    
const store = useStore()