简体   繁体   English

从子组件访问父道具/属性

[英]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. 我有一个看起来像下面代码的组件,我需要从SearchBox中了解它的父级( SearchContainer )的值是否设置了withFilter属性。

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可以检测它是否具有SearchFilter组件,这样我就可以摆脱该属性并使SearchBox也知道。

<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. 作为一种设计方法, SearchContainer应该有一个道具来决定是否显示SearchFilter

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. 您应该在代码中的SearchContainer render this.props.withFilter内使用this.props.withFilter

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

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