当前位置:首页 > React

react如何扩展组件功能

2026-01-24 23:26:23React

高阶组件(HOC)

高阶组件是一种函数,接收一个组件并返回一个新组件。通过包裹原始组件,可以注入额外的props或逻辑。适用于横切关注点(如权限控制、日志记录)。

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

自定义Hook

通过自定义Hook封装可复用的状态逻辑,供多个组件调用。适用于数据获取、表单处理等场景。

function useCounter(initialValue) {
  const [count, setCount] = useState(initialValue);
  const increment = () => setCount(count + 1);
  return { count, increment };
}
function MyComponent() {
  const { count, increment } = useCounter(0);
  return <button onClick={increment}>{count}</button>;
}

组合模式(Composition)

利用children或特定props将子组件/元素组合到父组件中。适用于UI布局或行为扩展。

function Card({ header, children }) {
  return (
    <div className="card">
      <div className="header">{header}</div>
      <div className="body">{children}</div>
    </div>
  );
}
// 使用
<Card header="Title">Content goes here</Card>

Render Props

通过函数prop动态决定渲染内容,实现逻辑与UI的解耦。适用于动态数据渲染。

function MouseTracker({ render }) {
  const [position, setPosition] = useState({ x: 0, y: 0 });
  return render(position);
}
// 使用
<MouseTracker render={({ x, y }) => <div>Mouse at {x}, {y}</div>} />

上下文(Context)API

通过React.createContext共享全局数据,避免逐层传递props。适用于主题、用户身份等跨层级数据。

const ThemeContext = React.createContext('light');
function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}
function Toolbar() {
  const theme = useContext(ThemeContext);
  return <div>Current theme: {theme}</div>;
}

组件继承(慎用)

通过类组件的extends继承父类功能,但React官方推荐组合优于继承。

react如何扩展组件功能

class BaseComponent extends React.Component {
  baseMethod() { /* ... */ }
}
class ChildComponent extends BaseComponent {
  render() {
    this.baseMethod();
    return <div>Extended</div>;
  }
}

标签: 组件功能
分享给朋友:

相关文章

vue电影功能实现

vue电影功能实现

Vue电影功能实现 数据获取与展示 使用Axios或Fetch API从电影API获取数据,例如TMDB或豆瓣API。在Vue组件的created或mounted生命周期钩子中发起请求,将返回的电影数…

vue实现组件封装

vue实现组件封装

Vue 组件封装方法 封装组件的基本步骤 创建独立的 .vue 文件,包含 template、script 和 style 三个部分。通过 props 接收父组件传递的数据,使用 $emit 触发自…

vue实现多级组件

vue实现多级组件

Vue 多级组件实现方法 在 Vue 中实现多级组件通常涉及父子组件通信、动态组件或递归组件等技术。以下是几种常见实现方式: 父子组件嵌套 通过逐层嵌套组件实现多级结构,适用于固定层级场景: &l…

vue实现粘贴功能

vue实现粘贴功能

实现粘贴功能的基本方法 在Vue中实现粘贴功能通常涉及监听paste事件,并处理剪贴板数据。以下是一个基础实现示例: <template> <div @paste="handl…

react如何删除组件

react如何删除组件

删除 React 组件的几种方法 条件渲染法 通过状态控制组件是否渲染。当状态为 false 时,组件会被移除: const [showComponent, setShowComponent…

php购物车功能的实现

php购物车功能的实现

实现购物车功能的基本方法 使用PHP实现购物车功能可以通过会话(Session)或数据库存储购物车数据。以下是两种常见方法的详细说明。 使用Session存储购物车数据 PHP的$_SESSION可…