【问题标题】:Problem with using useRef to add cssText in Typescript在 Typescript 中使用 useRef 添加 cssText 的问题
【发布时间】:2022-10-21 20:38:12
【问题描述】:

我在尝试使用useRef react hook 在 Typescript 中添加 cssText 时遇到问题。我已经在 J​​avascript 中测试了代码,它运行良好,但无法在 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 (

Screenshot of the error

我的依赖项如下:

"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"
  },

感谢是否有人可以分享对此问题的任何见解。

【问题讨论】:

  • ; 添加到此行的末尾 - const divRef = useRef&lt;HTMLDivElement&gt;(null)handleClick 函数的末尾。
  • 嗨@OriDrori,感谢您的回复。这对错误没有帮助。我添加了错误的屏幕截图。它在 cssText 之后突出显示 += 符号。
  • 为什么你必须为此“滥用”短路?一个简单的 if 语句将使它公正并使其更具可读性。

标签: javascript reactjs typescript react-hooks use-ref


【解决方案1】:

尝试

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

或者

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

因为&amp;&amp; 优先于+=

【讨论】:

    猜你喜欢
    • 2021-06-18
    • 2020-11-17
    • 2021-07-03
    • 2020-08-09
    • 2018-03-03
    • 2021-09-10
    • 2023-01-03
    • 2020-05-09
    • 2017-07-10
    相关资源
    最近更新 更多