当前位置:首页 > React

react如何重用组件

2026-02-26 08:24:16React

重用组件的核心方法

通过Props传递数据
父组件通过Props向子组件传递数据或函数,子组件接收后实现动态渲染。例如:

// 父组件
<Button text="Click Me" onClick={handleClick} />

// 子组件
const Button = ({ text, onClick }) => (
  <button onClick={onClick}>{text}</button>
);

组合组件(Children)
利用props.children实现容器组件与内容的解耦:

<Card>
  <h2>Title</h2>
  <p>Content</p>
</Card>

// Card组件实现
const Card = ({ children }) => (
  <div className="card">{children}</div>
);

高阶组件(HOC)模式

通过函数包装现有组件,扩展其功能:

react如何重用组件

const withLogger = (WrappedComponent) => {
  return (props) => {
    console.log('Rendered:', WrappedComponent.name);
    return <WrappedComponent {...props} />;
  };
};

const EnhancedButton = withLogger(Button);

自定义Hook复用逻辑

将组件逻辑提取为可复用的Hook:

const useToggle = (initialState = false) => {
  const [state, setState] = useState(initialState);
  const toggle = () => setState(!state);
  return [state, toggle];
};

// 在多个组件中使用
const [isOn, toggleIsOn] = useToggle();

组件继承与复合

避免继承,优先组合
React官方推荐组合而非继承。通过组件嵌套或Props组合实现功能复用:

react如何重用组件

// 通过特定Props组合功能
<Modal
  header={<CustomHeader />}
  body={<DataTable />}
  footer={<SaveCancelButtons />}
/>

Context跨层级复用

通过Context API共享全局状态或配置:

const ThemeContext = createContext('light');

// 提供者
<ThemeContext.Provider value="dark">
  <Toolbar />
</ThemeContext.Provider>

// 消费者
const ThemedButton = () => {
  const theme = useContext(ThemeContext);
  return <button className={theme}>Button</button>;
};

渲染属性(Render Props)

通过函数Prop动态决定渲染内容:

<MouseTracker
  render={(position) => (
    <p>Current position: {position.x}, {position.y}</p>
  )}
/>

// 实现
class MouseTracker extends React.Component {
  state = { x: 0, y: 0 };
  // ...跟踪鼠标逻辑
  render() {
    return this.props.render(this.state);
  }
}

原子化设计模式

将组件拆分为最小可复用单元(如Button、Icon、Input),通过Storybook等工具维护组件库,实现跨项目复用。

标签: 组件react
分享给朋友:

相关文章

react如何开发组件

react如何开发组件

React 组件开发基础 React 组件分为函数组件和类组件两种形式。函数组件是现代 React 开发的主流方式,结合 Hooks 可以实现完整功能。 函数组件示例: function Gree…

如何下载react

如何下载react

下载 React 的方法 通过 npm 或 yarn 安装 React 可以通过包管理器 npm 或 yarn 安装。确保已安装 Node.js(包含 npm),然后在项目目录中运行以下命令:…

react如何浮动

react如何浮动

使用 CSS 实现浮动 在 React 中实现浮动效果可以通过 CSS 的 float 属性完成。在组件的样式文件或内联样式中直接设置 float: left 或 float: right。…

如何用react

如何用react

使用React的基本步骤 安装Node.js和npm 确保系统已安装Node.js和npm。Node.js自带npm,可从官网下载安装包。安装完成后,通过命令行验证版本: node -v npm -…

如何启动react

如何启动react

安装Node.js 确保系统已安装Node.js(建议使用LTS版本),可通过官网下载并安装。安装完成后,在终端运行以下命令验证版本: node -v npm -v 创建React项目 使用官方工…

react 如何跳转

react 如何跳转

使用 React Router 进行页面跳转 React 应用中通常使用 react-router-dom 库实现页面跳转。以下是几种常见的跳转方式: 安装依赖 npm install rea…