如何解决如何从装饰器函数获取组件自己的道具
我的组件需要使用创建组件时要传递的属性(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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。