ホームページ  >  記事  >  ウェブフロントエンド  >  機能コンポーネントの反応で Props をレンダリングする

機能コンポーネントの反応で Props をレンダリングする

Patricia Arquette
Patricia Arquetteオリジナル
2024-09-30 12:31:02861ブラウズ

Render Props in react for functional components

In React, Render Props is a technique used to share logic between components using a function prop. Instead of using children or composition, a function is passed as a prop to render content dynamically. This approach works well with functional components and hooks.

Here’s an example of how to implement Render Props with functional components:

Example

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;

Explanation:

  • MouseTracker is a functional component that takes a render prop.
  • The render prop is a function that receives the mouse position and returns JSX.
  • The App component passes a function as the render prop, which displays the mouse's x and y coordinates.

This pattern allows for more flexibility in deciding how to render content based on logic inside the MouseTracker component.

以上が機能コンポーネントの反応で Props をレンダリングするの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。