简体   繁体   中英

Access parent prop / attribute from child component

I have a component that looks like the code below and I need a way from within SearchBox to know the value of it's parent ( SearchContainer ) has the withFilter attribute set.

Even better if there's a way for SearchContainer to detect if it has a SearchFilter component within it as well so I can get rid of that attribute and for SearchBox to know as well.

<SearchContainer withFilter>
    <SearchFilter>Filter Orders</SearchFilter>
    <SearchBox/>
</SearchContainer>

As a design approach, SearchContainer should have a prop that decides if it's showing SearchFilter or not.

var hasFilter = true;
return (
  <SearchContainer withFilter={hasFilter}>
      {withFilter ? <SearchFilter>Filter Orders</SearchFilter> : null}
      <SearchBox withFilter={hasFilter} />
  </SearchContainer>
);

You should use this.props.withFilter inside the render of SearchContainer in your code.

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