Heim >Web-Frontend >js-Tutorial >Rendern Sie Requisiten in Reaktion für funktionale Komponenten
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:
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;
This pattern allows for more flexibility in deciding how to render content based on logic inside the MouseTracker component.
Das obige ist der detaillierte Inhalt vonRendern Sie Requisiten in Reaktion für funktionale Komponenten. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!