简体   繁体   中英

How do I unmount only one of the children in this.props.children

So lets assume I have something simple that has a render with a return of:

<Sample>
    {this.props.children}
</Sample>

Now lets call this component Example and lets pass some child Props to it:

<Example>
  <ChildA />
  <ChildB />
</Example>

Now lets say I wanted to unmount (thus calling componentWillUnmount() ) ChildB . How would you go about doing it?

If you don't want to render ChildB , there is nothing you can do from Example (Parent component which takes what you pass as props.children). It just shows whatever is written inside this component.

// Parent component

<div> {this.props.children} </div>

// somewhere in your code, you imported Parent component and 

<Parent> Hello </Parent>

The point is this.props.children is only a way of saying if someone uses this component and if they put something in it , this component will show content where you put this.props.children. Nothing else. So this is not something Parent components do. They just show whatever the children are.

You question leads to another question : what if I want to show a component conditionally.

In this case you can do the following in your render methods :

{ yourConditionHere && <ComponentWhichWillMountIfConditionIsTrue /> } 

As a result, if your condition passes , your parent component which accepts children, will show this component or vice versa.

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