ESLint - 组件应该写成纯函数(反应首选/无状态函数) [英] ESLint - Component should be written as a pure function (react prefer/stateless function)
问题描述
ESLint在反应项目上给了我这个错误。
ESLint is giving me this error on a react project.
ESLint - 组件应该写成纯函数(反应首选/无状态函数)
它指向组件的第一行。
export class myComponent extends React.Component {
render() {
return (
//stuff here
);
}
}
如何摆脱此错误?
推荐答案
两种选择。
暂时禁用警告
(未经测试;有多种方法可以做到这一点。)
// eslint-disable-next-line react/prefer-stateless-function
export class myComponent extends React.Component {
...
}
使用纯无状态组件
返回值是将要呈现的内容(例如,您基本上是在编写基于类的组件的 render
方法:
The return value is what will be rendered (e.g., you're basically writing class-based component's render
method:
export const myComponent = () => {
return (
// JSX here
)
}
(如果那是你的话,可以使用非ES6表示法。)
(Or use non-ES6 notation if that's your thing.)
对于这样没有其他支持逻辑的组件,我更喜欢隐式返回,e。 g。,
For components like this with no other supporting logic I prefer the implicit return, e.g.,
export MyComponent = () =>
<div>
// Stuff here
</div>
这是一个偏好问题。我会说你应该遵循React命名约定,并保持所有组件以大写字母开头。
This is a matter of preference. I would say that you should follow React naming conventions, though, and keep all components starting with an upper-case letter.
ESLint可能会抱怨多行JSX表达式周围缺少parens,因此请禁用该规则或使用parens。
如果你需要道具,它们会作为参数传递给函数:
If you need props, they're passed in as the argument to the function:
const MyComponent = (props) =>
<div>
<Something someProp={props.foo} />
</div>
export MyComponent
为方便起见,您可以像往常一样对参数进行解构:
And you can destructure in the parameter as usual for convenience:
const MyComponent = ({ foo }) =>
<div>
<Something someProp={foo} />
</div>
如果使用本地变量,这可以使隐式返回更容易一些。除非您声明,否则您将收到有关缺少 PropTypes
的ESLint警告;因为它不是一个类,你不能简单地在类中使用 static propTypes
,它们必须附加到函数(许多人都喜欢它)。
This can make the implicit return a little easier if you were using local vars. You'll get an ESLint warning about missing PropTypes
unless you declare them; since it's not a class you cannot simply use static propTypes
in the class, they must be attached to the function (which many people prefer anyway).
这篇关于ESLint - 组件应该写成纯函数(反应首选/无状态函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!