[英]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:当我在 react 开发工具中寻找它时,我看到:
Is this because I need to extend React component?这是因为我需要扩展 React 组件吗? 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.
如果您命名函数(组件)然后将其导出,它将正确显示在 React Dev Tools 中。
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:要添加到 Michael Jaspers 的答案中,如果您想使用命名导入(而不是默认导出),您可以这样做:
const MyComponent = props => <div />
export { MyComponent }
The component will show in React DevTools with the correct name.该组件将在 React DevTools 中显示正确的名称。
Note: If you had exported the expression directly:注意:如果您直接导出了表达式:
export const MyComponent = props => <div />
This would then show as Anonymous
or Unknown
in React DevTools这将在 React DevTools 中显示为
Anonymous
或Unknown
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.我意识到原来的问题已经被正确回答了,但我只是想指出一个非常相似的问题,如果使用 React.memo() 或类似的函数,你可能会遇到。 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).该组件仍将在 devtools 和某些 React 错误消息(例如 prop-types 验证)中显示为
Anonymous
。
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.正如迈克尔所说,目前没有办法改变它在 devtools 检查器中显示为
<Unknown>
而不在导出之前命名函数。 But if this github issue gets addressed, there may be in the future.但是如果这个 github 问题得到解决,将来可能会有。
https://github.com/facebook/react-devtools/issues/1294 https://github.com/facebook/react-devtools/issues/1294
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.