简体   繁体   English

将道具传递给es6中的子组件

[英]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. 使用es6将props从父组件传递到子组件有点麻烦。

 // 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? 我是否需要将道具从Carousel传递到CarouselItem,然后传递到Title组件?

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. 在React 16.2和之前的版本中,您必须显式地将props向下传递到组件树以到达组件后代。

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. 从React 16.3开始,您可以使用ContextApi跳过此操作并注入状态以指定组件并规避实际的组件树。

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). ReduxMobx之类的库也可以使用此功能,它们利用了非官方的 上下文api (与16.3 中发布的api不同)。

Yes, the most straight-forward way would be to pass the prop through CarouselItem as you say. 是的,最直接的方法是将道具通过CarouselItem如您所说。

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. 为了解决这个问题,React 16.3中添加了一个新的上下文API,该API允许将数据向下传递到多个级别。 Here's a good blog post about that. 这是一篇很好的博客文章。

use spread operator {...props} 使用传播运算符{...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 CarouselItem是父级,Title是子级,从父级接收所有道具

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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