ren*_*kre 11 javascript typescript reactjs
在我的组件中,我有以下代码可以滚动到页面底部:
const el = useRef(null);
useEffect(() => {
if (el.current === null) { }
else
el!.current!.scrollIntoView({ block: 'end', behavior: 'smooth' });
if (props.loading != true)
props.fetchFeedbackTaskPageData(submissionId);
}, [])
Run Code Online (Sandbox Code Playgroud)
这个elref 附加到一个 div(在页面底部),如下所示:
<div id={'el'} ref={el}></div>
Run Code Online (Sandbox Code Playgroud)
但是,我收到以下错误:
“从不”类型上不存在属性“scrollIntoView”。TS2339
当我不使用时!,我收到此错误:
对象可能为“空”。TS2531
我检查了很多关于这个问题的帖子,但没有看到如何在使用useRefand时在 react 中处理这个问题scrollIntoView。有任何想法吗?
Mos*_*ian 21
您必须告诉 useRef 它将被分配给 null 以外的其他类型,例如useRef<null | number>(null)或在您的情况下useRef<null | HTMLElement>(null)。
问题是,通过将 null 作为默认值分配给 ref,typescript 只能猜测 ref 的类型将是它的初始值(null)——这就是为什么你会收到你提到的错误。一般来说,refs 不必是 DOM 组件,因此 useRef 的类型定义不假定它会被分配给一个。
Ars*_*rma 18
对于在 2020 年阅读本文的任何人来说
const el = useRef<null | HTMLDivElement>(null);
Run Code Online (Sandbox Code Playgroud)
并且不再:
const el = useRef<null | HTMLElement>(null);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9480 次 |
| 最近记录: |