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

How to get component own props from decorator function

我的组件需要使用我在创建组件时传递的属性 (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”。这很容易并且对应于 React 最佳实践。另外,您可以编写自己的钩子来连接商店。代码看起来像这样:

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