React类组件复用按钮传参报错:no-unused-expressions
React类组件方法触发ESLint no-unused-expressions错误解决办法
我在React类组件的render方法内两次调用applebutton方法并传入不同参数:
{this.applebutton('tutor')} {this.applebutton('student')}
applebutton方法的定义如下:
applebutton = (type) => { <div className="col-12 col-sm-12 mt-2"> <AppleLogin clientId={globalVariable.APPLE_ID} redirectURI="https://test.example.com/sign-up" usePopup={true} callback={(e) => this.getAppleToken(e, `${type}`)} // Catch the response scope="email name" responseMode="query" render={renderProps => ( <div className='btn btn-google' onClick={renderProps.onClick} disabled={renderProps.disabled} > <AppleFilled className='btn-apple' /> Continue with Apple </div> )} cookiePolicy={'single_host_origin'} /> </div> }
但触发了如下ESLint错误:
Expected an assignment or function call and instead saw an expression no-unused-expressions
问题出在applebutton箭头函数上:你写了JSX表达式,但没有返回它。箭头函数如果使用大括号包裹多行代码,必须显式声明return,否则内部的JSX就只是一个未被使用的表达式,正好违反了no-unused-expressions规则。
有两种解决方式:
方式一:添加显式return
给箭头函数加上return关键字,把JSX结构返回出去:
applebutton = (type) => { return ( <div className="col-12 col-sm-12 mt-2"> <AppleLogin clientId={globalVariable.APPLE_ID} redirectURI="https://test.example.com/sign-up" usePopup={true} callback={(e) => this.getAppleToken(e, `${type}`)} scope="email name" responseMode="query" render={renderProps => ( <div className='btn btn-google' onClick={renderProps.onClick} disabled={renderProps.disabled} > <AppleFilled className='btn-apple' /> Continue with Apple </div> )} cookiePolicy={'single_host_origin'} /> </div> ) }
方式二:使用箭头函数隐式返回
去掉箭头函数的大括号,用小括号包裹多行JSX,利用箭头函数的隐式返回特性:
applebutton = (type) => ( <div className="col-12 col-sm-12 mt-2"> <AppleLogin clientId={globalVariable.APPLE_ID} redirectURI="https://test.example.com/sign-up" usePopup={true} callback={(e) => this.getAppleToken(e, `${type}`)} scope="email name" responseMode="query" render={renderProps => ( <div className='btn btn-google' onClick={renderProps.onClick} disabled={renderProps.disabled} > <AppleFilled className='btn-apple' /> Continue with Apple </div> )} cookiePolicy={'single_host_origin'} /> </div> )
内容的提问来源于stack exchange,提问作者Ram prasad
相关产品推荐
相关产品推荐

