【问题标题】:Query selector for this component only仅针对该组件的查询选择器
【发布时间】:2021-09-18 11:29:15
【问题描述】:

我正在为我的 div 添加一个高度,如下所示:

  const parentRef = useRef();

  useEffect(() => {
    let collapseHeight = parentRef.current.scrollHeight   
    const collapse = document.querySelector('.collapse-content-parent')
    collapse.style.height = collapseHeight + "px" 
  }, []); 

当同一个组件有多个实例时,这只是选择页面上的第一个 div。

我想做一些事情,比如将 querySelector 换成我的 ref,所以它对组件是特定的:

  const parentRef = useRef();

  useEffect(() => {
    let collapseHeight = parentRef.current.scrollHeight   
    parentRef.style.height = collapseHeight + "px" 
  }, []); 

但上面的结果是:

TypeError: Cannot set properties of undefined (setting 'height')

【问题讨论】:

    标签: reactjs use-ref


    【解决方案1】:

    不要使用parentRef.style.height ,而是使用这个parentRef.current.style.height

    【讨论】:

    • 成功了,在这种情况下“current”是否等同于“this”?
    • 并非如此。使用 Ref hook ,你得到一个对象,通过观察它你可以看到里面有什么。就像 U 使用 API 一样。顺便说一句,在某些情况下,U 可能需要使用“currentTarget”。它与“当前”略有不同。你也应该检查一下。
    猜你喜欢
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 2014-07-31
    • 2013-06-02
    相关资源
    最近更新 更多