简体   繁体   中英

What pattern is this in React?

I'm seeing these sort of code in recent days:

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

Looking at the body of the Base , looks the code expects a functions which receives the argument which has baseuri . I'm not sure how one can implement the same. Also not sure what problem does it actually solves? Is there a name for this pattern?

Am I missing something here?

It's a render-props pattern and it's actually explained in the documentation . Your component could be implemented like so:

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>
);

In other words, SpecificComponent could say to Base component: "you give me the data and I tell you what to render" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM