简体   繁体   中英

Looping this.props.children how do I test their type?

In the following code snippet in a custom React component

React.Children.map(this.props.children), (child) => {
    if (predicate(child)) {
        // do stuff
    }
    else {
        // do other stuff
    }
}

predicate is a function that tests the child for certain properties or whatever. How can I write predicate to test what type of element a child is?

In the article, Send Props to Children in React you see the same pattern that I applied above, except his predicate function looks like child.type === RadioOption.type -- this doesn't work if I want to check against a type the child has inherited from.

In my case, I have StatelessModal -- child may be one of several different components that extends StatelessModal .

When I know that child is one of the Modal components that extends StatelessModal, I find that neither predicate = (child) => child instanceof StatelessModal nor predicate = (child) => child.type instanceof StatelessModal work.

I played around in the console and figured out this works:

predicate = (child) => child.type.prototype instanceof StatelessModal

While the type property of a ReactElement seems to be undocumented, it is reasonable to note that here, child is a ReactElement , and child.type is a ComponentClass (you may also find it may be a string or StatelessComponent ) -- the ComponentClass is the class that defines the component; if the component was created through inheritance, the classes prototype chain includes the inherited type which is revealed by instanceof

The answer accepted not work for me at all.

I've test several ways to check children type. The conclusion comes that:

predicate = (child) => child.type === StatelessModal

Worked for both class components and functional components in react@16.7 and react@16.8 in both develop and production env.

Further test cases in https://github.com/dancerphil/react-children-type

And https://dancerphil.github.io/react-children-type/ shows the conclusion of production build.

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