![](/img/trans.png)
[英]How to use useRef hook and getClientBoundingRect with React and Typescript?
[英]Error when trying to use React useref in typescript
使用 React 和 typescript 我正在構建一個選項卡組件,您可以在其中從頂部從左到右滾動選項卡鏈接並溢出:滾動集。 這適用於觸控板,但我需要為鼠標用戶實現一種方法,以便他們可以像在此 codepen 中一樣單擊和滾動: https://codepen.io/thenutz/full/VwYeYEE到目前為止我為選項卡鏈接的代碼它位於選項卡內容上方,如下所示:
<div className='container'>
<div className='flex-row'
sx={{ overflow: 'scroll',
'::-webkit-scrollbar': { display: 'none' },
display: flex,
flexDirection: 'row',
flexWrap: 'no-wrap' }}>
<div className='tabLinks'
sx={{display: 'flex', flexDirection: 'row', flexWrap: 'no-wrap'}}>
{React.Children.map(children, (child, index) => ( //LOOPS THROUGH TAB LINKS HERE ))}
</div>
</div>
</div>
tabLinks div 是需要通過觸控板和鼠標水平滾動的 div(單擊並拖動)
我第一次嘗試這樣做是使用 react useRef 為具有 ClassName 'tabLinks' 的 div 創建一個 ref
const ref = React.useRef<HTMLDivElement>(null)
然后將此 ref 傳遞給 tabLinks div,我嘗試按照 codepen 示例實現 onMouseDown 事件,但在下面遇到此錯誤:
Property 'offsetLeft' does not exist on type 'RefObject<HTMLDivElement>'
任何幫助將非常感激。
編輯:
這是我到目前為止所嘗試的:
const ref = React.useRef<HTMLDivElement>(null)
let startX
let scrollLeft
<div className='container'>
<div className='flex-row'
sx={{ overflow: 'scroll',
'::-webkit-scrollbar': { display: 'none' },
display: flex,
flexDirection: 'row',
flexWrap: 'no-wrap' }}>
<div
className='items'
sx={{
display: 'flex',
flexDirection: 'row',
flexWrap: 'no-wrap'
}}
ref={ref}
onMouseDown={e => {
isDown= true
const offset = ref.current?.offsetLeft || 0
startX = e.pageX - offset
scrollLeft = ref.current?.scrollLeft
}}
onMouseUp={e => {
isDown = false;
}}
onMouseLeave={e => {
isDown = false
}}
onMouseMove={e => {
if(!isDown) return;
e.preventDefault();
const x = e.pageX - (ref.current?.offsetLeft ?? 0)
const walk = (x - startX) * 3; //scroll-fast
ref.scrollLeft = scrollLeft - walk
console.log(walk)
}}
>
{React.Children.map(children, (child, index) => ( //LOOPS THROUGH TAB LINKS HERE ))}
</div>
</div>
</div>
我現在收到此錯誤
Uncaught TypeError: Cannot add property scrollLeft, object is not extensible
at onMouseMove (index.tsx:102)
at HTMLUnknownElement.callCallback (react-dom.development.js:149)
at Object.invokeGuardedCallbackDev (react-dom.development.js:199)
at invokeGuardedCallback (react-dom.development.js:256)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:270)
at executeDispatch (react-dom.development.js:561)
at executeDispatchesInOrder (react-dom.development.js:583)
at executeDispatchesAndRelease (react-dom.development.js:680)
at executeDispatchesAndReleaseTopLevel (react-dom.development.js:688)
at forEachAccumulated (react-dom.development.js:662)
const offset = ref.current?.offsetLeft?? 0;
同樣適用於:
scrollLeft = ref.current?.scrollLeft?? 0;
這確保了當當前 ref 為 null 時兩個變量都有一個數值。
您將需要 null 合並運算符。 如果您沒有可用的,請使用:
const offset = ref.current?.offsetLeft || 0; scrollLeft = ref.current?.scrollLeft || 0;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.