首頁  >  文章  >  web前端  >  在 React 中為功能元件渲染 Props

在 React 中為功能元件渲染 Props

Patricia Arquette
Patricia Arquette原創
2024-09-30 12:31:02861瀏覽

Render Props in react for functional components

在 React 中,Render Props 是一種使用函數 prop 在元件之間共享邏輯的技術。不使用子項或組合,而是將函數作為 prop 傳遞以動態呈現內容。這種方法適用於功能組件和鉤子。

以下是如何使用功能元件實作 Render Props 的範例:

例子

import React, { useState } from 'react';

// The component using render props
const MouseTracker = ({ render }) => {
  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });

  const handleMouseMove = (event) => {
    setMousePosition({
      x: event.clientX,
      y: event.clientY,
    });
  };

  return (
    <div style={{ height: '100vh' }} onMouseMove={handleMouseMove}>
      {render(mousePosition)}
    </div>
  );
};

// Component that consumes the render props
const App = () => {
  return (
    <div>
      <h1>Mouse Tracker</h1>
      <MouseTracker render={({ x, y }) => (
        <h2>Mouse Position: {x}, {y}</h2>
      )}/>
    </div>
  );
};

export default App;

解釋:

  • MouseTracker 是一個需要渲染道具的功能元件。
  • render prop 是一個接收滑鼠位置並傳回 JSX 的函數。
  • App 元件傳遞一個函數作為 render prop,它顯示滑鼠的 x 和 y 座標。

此模式可以更靈活地決定如何根據 MouseTracker 元件內部的邏輯呈現內容。

以上是在 React 中為功能元件渲染 Props的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn