![](/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.