这在 React 中是什么模式?



最近几天我看到了这些代码:

<Base>
{({ baseuri }) => (
<Location>
{({ navigate, location }) => {
. . . . 
}}
</Location>
)}
</Base>

查看Base的主体,看起来代码期望一个函数接收具有baseuri的参数。我不确定如何实现相同的方法。也不确定它实际上解决了什么问题?这种模式有名字吗?

我在这里错过了什么吗?

这是一种渲染道具模式,实际上在文档中进行了解释。您的组件可以像这样实现:

const Base = props => (
<article>
<header>
<h1>heading here</h1>
</header>
// treat "children" prop as a function and pass an object to it
{props.children({
baseuri: "https://reactjs.org/docs/render-props.html"
})}
</article>
);
const SpecificComponent = () => (
<Base>
// we know that "children" is expected to be a function which will receive an object as an argument. We also use destructuring to get variable from this object
{({ baseuri }) => (
<p>{baseuri}</p>
)}
</Base>
);

换句话说,SpecificComponent可以对组件Base:"你给我数据,我告诉你要渲染什么"。

最新更新