简体   繁体   中英

Type Checking React Children

Question

How can I confirm that a react element received through props (like children for example) is of a given type in my render method?

Example:

Say I have a List element and a ListItem element. In the render method of List , I want to look for all of the children that were passed and do something special with any children that are ListItem s.

I did find an implementation that works, but only after trial and error. See the code below. (React 15.4.2)

List.jsx

import ListItem from 'list-item';

...

React.Children.map(children, child => {
  console.log(child);     // function ListItem() { ... }
  console.log(ListItem);  // function ListItem() { ... }

  if (isListItem(child)) {
    return (...);
  }
  return child;
})

// this implementation does not work
isListItem(element) {
  return (element.type === ListItem);
}

// this implementation does work, but might break if I'm using something like uglify or if I use `react-redux` and `connect()` ListItem (as that will change the display name)
isListItem(element) {
  return (element.type.displayName === 'ListItem');
}

// this implementation does work
isListItem(element) {
  return (element.type === (<ListItem />).type);
}

ListItem.jsx

class ListItem expends React.component {
  ...
}

export default ListItem;

So, the last implementation seems to work, but why doesn't the first implementation work? I can't find any material relating to this in the react documentation, though I did find some stack overflow questions about the same thing. The answers provided in those questions, however, indicate that the first implementation should work (though they are for older versions of React)

Relevant Links

While this question is old, I ran into this problem while using react-hot-loader and took me a while to finally find this GitHub issue explaining why it behaved this way.

This is intended, react-hot-loader@3 patches React.createElement(<ImportedComponent />) is equivalent to React.createElement(ImportedComponent) so that it returns an element of a proxy wrapper for your components instead of the original component, this is part of allows to replace methods on the component without unmounting.

- @nfcampos

In addition to the methods you discovered, RHL now provides a areComponentsEqual() function with a dedicated section in their README .

import { areComponentsEqual } from 'react-hot-loader'

const element = <Component />
areComponentsEqual(element.type, Component) // true

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