[英]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.