ESLint在react项目上给了我这个错误。
ESLint-组件应被编写为纯函数(react preferred / stateless function)
它指向组件的第一行。
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方法:
render
export const myComponent = () => { return ( // JSX here ) }
(如果那是您的事,请使用非ES6表示法。)
对于没有其他支持逻辑的此类组件,我更喜欢隐式返回,例如,
export MyComponent = () => <div> // Stuff here </div>
这是优先事项。我要说的是,您应该遵循React命名约定,并保持所有组件以大写字母开头。
ESLint可能会抱怨缺少多行JSX表达式周围的括号,因此请禁用该规则或使用括号。
如果需要道具,它们将作为参数传递给函数:
const MyComponent = (props) => <div> <Something someProp={props.foo} /> </div> export MyComponent
为了方便起见,您可以像往常一样对参数进行解构:
const MyComponent = ({ foo }) => <div> <Something someProp={foo} /> </div>
如果您使用的是本地var,这可以使隐式返回变得容易一些。PropTypes除非声明它们,否则您会收到有关丢失的ESLint警告。因为它不是一个类,所以您不能简单地static propTypes在该类中使用它,因此必须将它们附加到该函数上(无论如何,这还是很多人喜欢的)。
PropTypes
static propTypes