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

React中container?.appendChild触发no-unused-expressions错误的修复方案

问题描述

开发React应用时,以下代码中的container?.appendChild(canvas);行触发ESLint错误:Expected an assignment or function call and instead saw an expression no-unused-expressions,关闭ESLint检查后代码可正常运行,尝试过在该行前加return、用()包裹函数均无效,需修复该问题。

现有代码

createCanvas(container) {
  if (
    this.width !== undefined
    && this.height !== undefined) {
      const canvas = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
      canvas.style.position = 'relative';
      canvas.setAttribute('width', `${this.width}px`);
      canvas.setAttribute('height', `${this.height}px`);
      const halfWidth = this.width / 2;
      const halfHeight = this.height / 2;
      this.yLine = canvas.appendChild(this.createLine(halfWidth, 0, halfWidth, this.height, '2px'));
      this.xLine = canvas.appendChild(this.createLine(0, halfHeight, this.width, halfHeight, '2px'));
      container?.appendChild(canvas);
      this.svgCanvas = canvas;
  }
}

错误原因

ESLint的no-unused-expressions规则禁止未被使用的表达式。container?.appendChild(canvas)是可选链表达式:当container为null或undefined时,整个表达式结果为undefined,且没有被赋值或作为参数传递,ESLint会判定这是“未使用的表达式”。

修复方案

方案1:用条件判断替代可选链(推荐)

直接检查container是否存在,再执行appendChild,写法清晰且符合ESLint规则:

if (container) {
  container.appendChild(canvas);
}

方案2:修改ESLint规则允许可选链表达式

若希望保留可选链写法,可在ESLint配置中开启allowOptionalChain选项(要求ESLint版本≥7.5.0):
在.eslintrc.js或其他ESLint配置文件中添加:

module.exports = {
  // ...其他配置
  rules: {
    "no-unused-expressions": ["error", { "allowOptionalChain": true }]
  }
};

方案3:将表达式赋值给变量(不推荐)

把可选链表达式的结果赋值给一个变量(即使变量不用),可绕过ESLint检查,但可能触发no-unused-vars规则,不推荐使用:

// 不推荐,可能触发no-unused-vars错误
const _ = container?.appendChild(canvas);

为什么之前的尝试无效

  • 在该行前加return:虽能让表达式被使用,但appendChild返回的是添加的DOM节点,而createCanvas函数可能不需要返回值,不符合函数设计逻辑;同时若container为null,会返回undefined,可能引发其他问题。
  • 用()包裹:(container?.appendChild(canvas))本质还是未被使用的表达式,ESLint依然会报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 11:01:09