在Typescript中使用useRef添加cssText的问题



我遇到了一个问题,当尝试使用useRefreact钩子在Typescript中添加cssText。我已经在Javascript中测试了代码,它工作得很好,但无法在Typescript中工作。我的代码如下。当我点击该按钮时,代码将改变div的背景颜色。

import {useRef} from 'react';
function App() {
const divRef = useRef<HTMLDivElement>(null)
const handleClick = () => {
divRef.current && divRef.current.style.cssText += "background-color: blue";
}
return (
<div className="App" ref={divRef}>
<button onClick={handleClick}>Click me</button>
</div>
);
}

我得到了以下错误信息:

ERROR in src/App.tsx
Line 6:51:  Parsing error: ';' expected
webpack compiled with 2 errors
ERROR in src/App.tsx:6:52
TS1005: ';' expected.
4 |   const divRef = useRef<HTMLDivElement>(null);
5 |   const handleClick = () => {
> 6 |     divRef.current && divRef.current.style.cssText += "background-color: blue";
|                                                    ^^
7 |   };
8 |
9 |   return (

错误截图

我的依赖项如下:

"dependencies": {
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.1.1",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.0",
"@types/node": "^16.11.33",
"@types/react": "^18.0.8",
"@types/react-dom": "^18.0.3",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-scripts": "5.0.1",
"typescript": "^4.6.4",
"web-vitals": "^2.1.4"
},

如果有人能分享任何关于这个问题的见解,我将不胜感激。

Try

if (divRef.current) {
divRef.current.style.cssText += 'background-color: blue';
}

divRef.current && (divRef.current.style.cssText += "background-color: blue");

因为&&优先于+=

最新更新