You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React箭头函数定义组件报错,求保留箭头函数的解决方案

解决方案

修复箭头函数体写法错误

你的代码中箭头函数使用了{ return ... }的块级写法,触发了ESLint的arrow-body-style规则警告。直接改为隐式返回即可解决,同时保留箭头函数形式:

const Navbar = () => (
  <div>
    <ul>
      {LINKS.map(item => (
        <li key={item.to}>
          <Link to={item.to}>{item.text}</Link>
        </li>
      ))}
    </ul>
  </div>
);

修复组件定义形式错误

这个错误来自react/function-component-definition规则,默认可能强制要求用函数声明定义组件。若要保留箭头函数,需修改ESLint配置文件(如.eslintrc.js或.eslintrc.json),调整规则允许箭头函数形式:

.eslintrc.js 配置示例

module.exports = {
  // 其他配置项...
  rules: {
    // 其他规则...
    "react/function-component-definition": [
      2,
      {
        namedComponents: "arrow-function",
        unnamedComponents: "arrow-function"
      }
    ]
  }
};

.eslintrc.json 配置示例

{
  "rules": {
    "react/function-component-definition": [
      2,
      {
        "namedComponents": "arrow-function",
        "unnamedComponents": "arrow-function"
      }
    ]
  }
}

最终完整代码

结合上述修改后的完整代码:

import React from 'react';
import { Link } from 'react-router-dom';

const LINKS = [
  { to: '/', text: 'Home' },
  { to: '/starred', text: 'Starred' },
];

const Navbar = () => (
  <div>
    <ul>
      {LINKS.map(item => (
        <li key={item.to}>
          <Link to={item.to}>{item.text}</Link>
        </li>
      ))}
    </ul>
  </div>
);

export default Navbar;

内容的提问来源于stack exchange,提问作者Akshay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 16:05:34