React有什么模式?

时间:2018-06-02 08:44:44

标签: reactjs

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

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

查看Base的主体,看起来代码需要一个接收baseuri参数的函数。我不确定如何实现同样的目标。还不确定它实际解决了什么问题?这个模式有名字吗?

我在这里错过了什么吗?

1 个答案:

答案 0 :(得分:1)

这是一个渲染道具模式,它实际上是在documentation中解释的。您的组件可以像这样实现:

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组件说:“你给我数据,我告诉你要渲染什么”