我使用 React 构建了一个大型应用程序,它变得越来越难以调试(我也使用样式化组件),我想要一种在检查 dom 时快速识别元素和组件的方法。
带样式的组件会生成随机散列,这意味着有时很难找到确切的组件。
我想知道是否有人可以建议是否使用 id、类或数据属性(或组合是最好的),因为标识符主要用于调试和测试,是否有好的方法将它们撕掉生产包?也许使用 webpack 或其他替代方案。
最佳答案
Styled Components 附带了一个 Babel 插件,您可以使用它来更好地调试。 你可以安装它:
npm install --save-dev babel-plugin-styled-components
您可以 add it to babel config喜欢:
{
"plugins": ["babel-plugin-styled-components"]
}
这将在 React DevTools 中显示以文件名为前缀的样式化组件的名称。这有助于所有 styled.DOMNode
出现在您的开发工具中。
来自docs :
adds support for showing your components' real name in the React DevTools. Consider writing a styled component that renders a button element, called MyButton. It will normally show up as for all of your components, but with this plugin they show .
文档还指定了配置这些的选项,例如 displayName
和 fileName
,您可以找到 here
关于javascript - 在 React 中使用类名、ID 和数据属性时的最佳实践是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52580352/