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 ({render(mousePosition)}); }; // Component that consumes the render props const App = () => { return (); }; export default App;Mouse Tracker
( Mouse Position: {x}, {y}
)}/>
This pattern allows for more flexibility in deciding how to render content based on logic inside the MouseTracker component.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3