React JS:Render函数内添加功能代码遇语法错误求助
解决React循环渲染的ESLint语法错误
你的代码存在两个导致ESLint语法报错的问题:
- map回调未返回JSX元素:当箭头函数用大括号包裹函数体时,必须显式使用
return返回组件;或者将大括号替换为圆括号,让箭头函数自动返回表达式结果。 - 冗余分号:map语句末尾的分号在JSX表达式块中属于多余代码,会被ESLint判定为语法问题。
修正后的代码如下:
const renderComponentButtons = () => { const { questionNo } = componentContent; if (componentContent?.button) { return ( <fieldset className="col-lg-8" aria-labelledby={componentContent?.ariaLabelledby}> {Object.keys(componentContent.button).map((key) => ( <ButtonAction key={key} data-testid="getDisputeQst1" onClick={() => { return componentContent.button[key]?.displayModal === 'True' ? openModalWindow(questionNo, key) : moveToNextQuestion(componentContent.button[key].buttonText); }} > {componentContent.button[key].buttonText} </ButtonAction> ))} </fieldset> ); } return null; };
关键修正说明:
- 将map回调函数的
{}替换为(),让箭头函数自动返回内部的JSX元素,无需显式写return - 移除了map语句末尾的多余分号
- 可选择性简化
onClick内的return(三元表达式本身会返回结果,return可以省略)
内容的提问来源于stack exchange,提问作者Arun Kumar
相关产品推荐
相关产品推荐

