TS18007:JSX 表达式不能使用逗号运算符。你的意思是写一个数组?

TS18007: JSX expressions may not use the comma operator. Did you mean to write an array?

将 TypeScript 添加到我的 React 应用程序后,我开始收到这些错误:

TS18007: JSX expressions may not use the comma operator. Did you mean to write an array?

以下是我遇到此错误的代码库中的一些片段:

 style={pageStyles.fundContainer, { padding: updatedAt ? '8px 16px 20px 16px' : '16px 16px 20px 16px' }}

另一个例子:

className={ 'materialize-textarea', getErrorClass(errors, 'state') }

我是这个代码库的新手,但乍一看我能感觉到上面的代码片段是错误的,但找不到任何有效的东西。

如果能对此有所了解,我们将不胜感激。

不要使用 , 而是执行以下操作。

对于style

 style={{...pageStyles.fundContainer, padding: updatedAt ? '8px 16px 20px 16px' : '16px 16px 20px 16px' }}

对于 className:

className={'materialize-textarea'+ ' '+ getErrorClass(errors, 'state')}

(我假设 getErrorClass(errors, 'state') 会 return 一个 string

我不太清楚代码的作者想做什么。像这样的代码...

style={pageStyles.fundContainer, { padding: updatedAt ? '8px 16px 20px 16px' : '16px 16px 20px 16px' }}

...意味着“评估pageStyles.fundContainer,但随后完全忽略它。然后将第二个对象分配给样式道具”。换句话说,结果与只是做没有什么不同:

style={{ padding: updatedAt ? '8px 16px 20px 16px' : '16px 16px 20px 16px' }}

因为我不明白他们想做什么,所以我只能猜测。也许他们试图将两个对象合并在一起?在这种情况下,正确的方法是:

style={{
  ...pageStyles.fundContainer,
  padding: updatedAt ? '8px 16px 20px 16px' : '16px 16px 20px 16px'
}}
// OR:
style={Object.assign(
  {}, 
  pageStyles.fundContainer, 
  { padding: updatedAt ? '8px 16px 20px 16px' : '16px 16px 20px 16px' }
)}

对于 className 的情况,也许他们试图连接字符串?

style={'materialize-textarea ' + getErrorClass(errors, 'state')}
// OR:
style={`materialize-textArea ${getErrorClass(errors, 'state')}`}