渲染 Props
一句话解释
渲染 Props 是模式哪里组件 takes 函数 as prop and calls 它到 determine 什么到 渲染 — 方式到 share 渲染 logic.
用大白话说
The render props pattern uses a function prop to share code between components. The component with the logic calls the function prop, passing it data, and the function returns JSX.
<MouseTracker 渲染={(mouse) => <Cat 位置={mouse} />} /> — MouseTracker tracks the mouse position and calls the 渲染 prop with the current position. The parent decides what to render with that data.
Like HOCs, render props were a pre-Hooks pattern for sharing stateful logic. Today, custom Hooks are preferred — they are simpler and don't require wrapper components or function props. But render props are still useful when the logic is inherently about rendering (like animation libraries).
示例
function MouseTracker({ render }) {
const [pos, setPos] = useState({ x: 0, y: 0 });
return (
<div onMouseMove={(e) => setPos({ x: e.clientX, y: e.clientY })}>
{render(pos)}
</div>
);
}
<MouseTracker render={(pos) => <p>Mouse at {pos.x}, {pos.y}</p>} />MouseTracker manages mouse 位置 and calls 渲染 prop 使用它. caller decides 什么到 display.
相关术语
相关资源
相关课程
- React 最佳实践
学习渲染 Props and modern alternatives.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。