当前位置:首页 > 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)模式

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

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组合实现功能复用:

// 通过特定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动态决定渲染内容:

react如何重用组件

<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
分享给朋友:

相关文章

vue实现穿梭框树组件

vue实现穿梭框树组件

Vue 穿梭框树组件实现 穿梭框树组件通常结合了树形结构和穿梭框功能,允许用户在左右两栏之间移动树节点数据。以下是基于 Vue 的实现方案: 核心功能设计 数据结构 树形数据通常采用嵌套结构,例如:…

如何优化react

如何优化react

优化 React 性能的方法 使用 React.memo 或 PureComponent 对于函数组件,使用 React.memo 进行记忆化,避免不必要的重新渲染。类组件可以使用 PureCompo…

react如何运行

react如何运行

运行React项目的步骤 安装Node.js 确保系统已安装Node.js(建议版本12以上),可从官网下载并安装。Node.js自带npm包管理器,用于后续依赖安装。 创建React项目 使用官方…

react如何encode

react如何encode

React 中编码的实现方式 在 React 中,编码通常涉及对 URL、HTML 实体或特殊字符的处理。以下是几种常见的编码方法: 使用 encodeURIComponent 进行 URL 编码…

react就业如何

react就业如何

React 就业市场现状 React 作为当前主流前端框架之一,就业需求持续旺盛。国内外互联网企业、中大型公司以及初创团队普遍采用 React 技术栈,尤其在 Web 应用、移动端(React Nat…

uniapp组件

uniapp组件

uniapp组件基础概念 uniapp的组件系统基于Vue.js,支持跨平台开发(H5、小程序、App等)。组件分为内置基础组件(如<view>、<button>)和自定义组件…