简体   繁体   中英

React Dev tools show my Component as Unknown

I have the following simple component:

import React from 'react'
import '../css.scss'

export default (props) => {
  let activeClass = props.out ? 'is-active' : ''
  return (
    <div className='hamburgerWrapper'>
      <button className={'hamburger hamburger--htla ' + activeClass}>
        <span />
      </button>
    </div>
  )
}

When I look for it in the react dev tools, I see:

在此处输入图片说明

Is this because I need to extend React component? Do I need to create this as a variable and do so?

This happens when you export an anonymous function as your component. If you name the function (component) and then export it, it will show up in the React Dev Tools properly.

const MyComponent = (props) => {}
export default MyComponent;

To add to Michael Jaspers answer, if you want to use a named import (instead of default export), you can do like so:

const MyComponent = props => <div />
export { MyComponent }

The component will show in React DevTools with the correct name.

Note: If you had exported the expression directly:

export const MyComponent = props => <div />

This would then show as Anonymous or Unknown in React DevTools

I realise the original question has been correctly answered already, but I just wanted to note a very similar issue you may encounter if using React.memo() or similar function. Consider the following code:

const MyComponent = React.memo(props => <div>Hello</div>)
export default MyComponent

The component will still display as Anonymous in devtools and certain React error messages (eg prop-types validation).

Ensuring that the Component is defined before trying to memoise it resolves this issue, eg:

const MyComponent = props => <div>Hello</div>
export default React.memo(MyComponent)

Currently there's no way to change it from showing up as <Unknown> in the devtools inspector without naming the function before exporting it, as Michael said. But if this github issue gets addressed, there may be in the future.

https://github.com/facebook/react-devtools/issues/1294

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