最近几天我看到了这些代码:
<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
说:"你给我数据,我告诉你要渲染什么"。