我正在开发一个使用 Webpacker 构建 ES6 React 应用程序的项目。我们正在使用 ESLint 通过一些预提交 Hook 来保持我们的脚本整洁,但有一个问题我无法解决。我们使用了几个 React.Component
子类,ESLint 未将它们检测为 Components
。
示例组件:
/* AsyncComponent.jsx */
export default class AsyncComponent extends React.Component {
// Sub-classes will define _render() instead of render()
render() {
if (this.isLoaded()) {
this._render();
}
}
// "Virtual" functions which must be defined by sub-class
// isLoaded() {}
// load() {}
// _render() {}
}
/* MyComponent.jsx */
export default class MyComponent extends AsyncComponent {
// This works, but is not parsed as a Component by ESLint
// Define our "virtual" AsyncComponent functions
isLoaded() {}
load() {}
_render() {}
}
我的问题: 我想知道是否可以配置 ESLint 来检测 AsyncComponent
子类,例如 MyComponent
作为 React.Component
子类化并应用与其他 Components
相同的规则。
红利问题:这可能会导致此特定示例使用的 _render()
方法出现问题,因此如果我可以覆盖 eslint- react 规则期望 _render()
而不是 AsyncComponent
子类中的 render()
。
来自package.json
的相关依赖:
"eslint": "^5.11.1",
"eslint-config-airbnb": "^17.1.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-jsx-a11y": "^6.1.2",
"eslint-plugin-react": "^7.12.2",
"eslint-plugin-promise": "^4.0.1",
"eslint-plugin-react-redux": "^3.0.1",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"react-redux": "^6.0.0",
"redux": "^4.0.1",
来自.eslintrc
的相关配置:
"extends": [
"airbnb",
"plugin:react-redux/recommended",
"plugin:promise/recommended"
],
"parser": "babel-eslint",
"parserOptions": {
"ecmaVersion": 8,
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"impliedStrict": true,
"classes": true
}
},
"env": {
"browser": true,
"node": true,
"jquery": true,
"jest": true
},
"plugins": [
"react-redux",
"promise"
],
最佳答案
我不确定你想要达到什么目的。我想你可以试试 return super.render()
render() {
if (this.isLoaded()) {
super.render()
}
}
但是像上面说的那样扩展组件是个坏主意,对这种东西使用 hooks、Hocs 或 renderProps 模式,我知道这可能会造成混淆,特别是如果你来自“OO”背景,但考虑你所做的方法会比它的值(value)更麻烦。
关于javascript - 我可以将我的 React.Component 子类添加到 ESLint 规则吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55593734/