繁体   English   中英

我可以将我的 React.Component 子类添加到 ESLint 规则吗?

[英]Can I add my React.Component subclass to ESLint rules?

我正在开发一个使用 Webpacker 构建 ES6 React 应用程序的项目。 我们正在使用 ESLint 通过一些预提交钩子来保持我们的脚本整洁,但是有一个我无法解决的问题。 我们有几个我们使用的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 规则以期望在AsyncComponent子类中使用_render()而不是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()
    }
  }

但是像上面所说的那样扩展这样的组件是一个坏主意,对这类东西使用钩子、Hocs 或 renderProps 模式,我知道这可能会令人困惑,尤其是如果您来自“OO”背景,但采用这种方法已经做了会比它的价值更多的麻烦。

感谢@fard 的建议。 我试图以错误的方式做到这一点......似乎React 高阶组件是完成我在这里尝试实现的目标的正确方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM