首页 > 解决方案 > c.getBoundingClientRect 不是函数

问题描述

我正在使用语义可见性但我有这个错误我不知道我将传递给我的函数参数

有人可以帮我解决这个问题吗?

const handleOverlayRef = (c) => {
  console.log(c);
  if (!overlayRect) {
    setOverlayRect({ overlayRect: _.pick(c.getBoundingClientRect(), 'height', 'width') })
  }
}
      <Visibility
        offset={80}
        once={false}
        onTopPassed={()=> stickOverlay()}
        onTopVisible={()=>unStickOverlay()}
        style={overlayFixed ? { ...overlayStyle, ...overlayRect } : {}}
      />

      <div ref={() => handleOverlayRef()} style={overlayFixed ? fixedOverlayStyle : overlayStyle}>
        <Menu
          icon='labeled'
          style={overlayFixed ? fixedOverlayMenuStyle : overlayMenuStyle}
          vertical
        >
          <Menu.Item>
            <Icon name='twitter' />
            Twitter
          </Menu.Item>

          <Menu.Item>
            <Icon name='facebook' />
            Share
          </Menu.Item>

          <Menu.Item>
            <Icon name='mail' />
            Email
          </Menu.Item>
        </Menu>
      </div>

错误:

TypeError:c.getBoundingClientRect 不是函数

标签: reactjs

解决方案


当我们使用 ref 时,我们应该首先声明它,如下所示:

    function Component = props => { 
           const myRef = React.useRef(); 

        const myMethod = event => {
           const {height, width, x, y} = myRef.current.getBoundingClientRect();
           console.log(height, width, x, y);
         }

        return (
       <div ref={myRef} style={overlayFixed ? fixedOverlayStyle : overlayStyle}>


       </div>
     )
 }

推荐阅读