简体   繁体   中英

Passing props to child components in es6

Having a bit of trouble passing props down from a parent component to a child component with es6.

 // Parent component const Carousel = () => ( <nav className="projects-nav"> <div className="projects-nav__wrapper"> <CarouselItem title="Mowat" client="Jon Mowat" image="/images/mowat.jpg" icon="images/icons/video.svg" url="/mowat.html" /> </div> </nav> ); // Child component const CarouselItem = () => ( <div className="project project--mowat"> <Letter /> <Title /> <Description /> </div> ); // Child component where prop is inserted const Title = ({ title }) => ( <a href="/mowat.html" className="project__title"> <h2>{title}</h2> </a> ); 

Do I need to pass the prop from the Carousel to the CarouselItem then to the Title component?

The answer is yes.

With React 16.2 and before, you have to explicitly pass props down the component tree to reach a component descendant.

const CarouselItem = ({ title }) => (
  <div className="project project--mowat">
    <Letter />
    <Title title={title} />
    {/*    ^^^^^^^^^^^^^ pass prop to grandchild */}
    <Description />
  </div>
);

Starting from React 16.3, you can use the ContextApi to skip this and inject state to designate components and circumvent the actual component tree.

This functionality is also available with libraries like Redux or Mobx which take advantage of the unofficial context api (not the same as the one coming out in 16.3).

Yes, the most straight-forward way would be to pass the prop through CarouselItem as you say.

const CarouselItem = (props) =>
    <div className="project project--mowat">
        <Letter />
        <Title title={props.title} />
        <Description />
    </div>

However, doing this multiple levels deep can get a little unwieldy, and has even gotten the name "prop drilling". To solve that, a new context API is being added in React 16.3, which allows passing data down through multiple levels. Here's a good blog post about that.

use spread operator {...props}

const CarouselItem = (props) => (
  <div className="project project--mowat">
    <Letter />
    <Title {...props}/>
    <Description />
  </div>
);

CarouselItem is parent and Title is child recieving all props from parent

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