」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 在 React 中為功能元件渲染 Props

在 React 中為功能元件渲染 Props

發佈於2024-11-07
瀏覽:335

Render Props in react for functional components

在 React 中,Render Props 是一種使用 function 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 (
    
{render(mousePosition)}
); }; // Component that consumes the render props const App = () => { return (

Mouse Tracker

(

Mouse Position: {x}, {y}

)}/>
); }; export default App;

解釋:

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

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

版本聲明 本文轉載於:https://dev.to/imyusufakhtar/render-props-in-react-for-functional-components-2a3k?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3