You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建接收组件参数的React HOC并拆分至独立文件

How to Split a Store-Wrapping HOC into a Separate Reusable File in React

Got it, let's fix this so you have a flexible, reusable HOC that lives in its own file and can wrap any component you want—instead of being tied to SignedMotor in a single file. Here's how to do it step by step:

Step 1: Create the Standalone HOC File

First, make a new file (e.g., withStore.tsx if you're using TypeScript, or withStore.jsx for plain JS) to house your generic HOC. This file will import your Store component and define the wrapper logic.

// src/hocs/withStore.tsx
import React from 'react';
import Store from '../path-to-your-store-component'; // Replace with your actual Store import path

// Generic HOC that accepts any component and wraps it in Store
const withStore = <P extends object>(Component: React.ComponentType<P>) => {
  // Return a new component that passes through all props to the wrapped component
  return (props: P) => (
    <Store>
      <Component {...props} />
    </Store>
  );
};

export default withStore;

Notes for Plain JavaScript

If you're not using TypeScript, you can simplify the type definitions:

// src/hocs/withStore.jsx
import React from 'react';
import Store from '../path-to-your-store-component';

const withStore = (Component) => {
  return (props) => (
    <Store>
      <Component {...props} />
    </Store>
  );
};

export default withStore;

Step 2: Use the HOC with Your Components

Now you can import this HOC into any component file and wrap your target component (like MyComponent or SignedMotor) with it.

Example with MyComponent:

// src/components/MyComponent.tsx
import React from 'react';
import withStore from '../hocs/withStore';

const MyComponent = (props) => {
  return <div>my component</div>;
};

// Wrap the component with our Store HOC before exporting
export default withStore(MyComponent);

Example with SignedMotor:

// src/components/SignedMotor.tsx
import React from 'react';
import withStore from '../hocs/withStore';

const SignedMotor = (props) => {
  // Your SignedMotor component logic here
  return <div>Signed Motor Component</div>;
};

export default withStore(SignedMotor);

What Changed?

  • Your original HOC was hardcoded to only wrap SignedMotor—now this generic version accepts any component as input, making it reusable across your app.
  • The HOC lives in its own file, so you can import and use it wherever you need to wrap a component with Store.
  • All props passed to the wrapped component are forwarded correctly, so you don't lose any functionality.

内容的提问来源于stack exchange,提问作者Pedro Morais

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:34:43