reactjs 如何解决“element.getBoundingClientRect不是函数”

qij5mzcb  于 2023-02-08  发布在  React
关注(0)|答案(2)|浏览(491)

我有一个组件,并希望在鼠标悬停在"Persona"元素上时使用Office-UI-Fabric-react组件"Callout"。
如果引用包含"Persona"元素的"div","Callout"就可以工作
(使用ref={this.setPersonaRef}),
但是"角色"元素中的componentRef={this.setPersonaRef}导致
CalloutContent. componentDidMount()中出现异常:类型错误:元素. getBoundingClientRect不是函数
以下是组件:

import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Persona,PersonaSize } from 'office-ui-fabric-react/lib/Persona';
import { Callout } from 'office-ui-fabric-react/lib/Callout';

import {IHoverPersonaProps} from './IHoverPersonaProps';
import {IHoverPersonaState} from './IHoverPersonaState';

export default class HoverPersona extends React.Component < IHoverPersonaProps,IHoverPersonaState > {
   private personaRef: any;
  
    constructor(props) {
        super(props);

        this.state = {
            hover: false
        };

        this.setPersonaRef = this.setPersonaRef.bind(this);
    }

    setPersonaRef(element) {
        this.personaRef = element; 
    }

    MouseEnter() {
        this.setState({hover:true})
    } 
    
    MouseLeave() {
        this.setState({hover:false})
    }

    public render() : React.ReactElement < IHoverPersonaProps > {
            return  <div onMouseEnter={this.MouseEnter.bind(this)} onMouseLeave={this.MouseLeave.bind(this)}   >
                      <Persona {...this.props} size={PersonaSize.extraSmall} primaryText={this.props.value} componentRef={this.setPersonaRef} />
                      { this.state.hover && 
                       <Callout
                        className="ms-CalloutExample-callout"
                        ariaLabelledBy={'callout-label-1'}
                        ariaDescribedBy={'callout-description-1'}
                        coverTarget={false} 
                        gapSpace={0} 
                        target={this.personaRef}
                        setInitialFocus={true}
                        >
                            <div className="ms-CalloutExample-header">
                                <p className="ms-CalloutExample-title" id={'callout-label-1'}>
                                Test
                                </p>
                            </div>
                            <div className="ms-CalloutExample-inner">
                            <Persona {...this.props} size={PersonaSize.large} primaryText={this.props.value}  /> 
                            </div>
                       </Callout>
                       
                     }
                    </div>;     
    }
}

如何解决异常?

3qpi33ja

3qpi33ja1#

因为要使用getBoundingClientRect或其他类似的方法,您需要指向refcurrent属性。
来自文件:

    • useRef**(或简单类ref)返回可变ref对象,该对象的. current属性已初始化为传递的参数**(initialValue)**。返回的对象将在组件的整个生存期内保持。

示例:

function App() {
  const inputRef = useRef();
  const scrollHandler = _ => {
    console.log(inputRef.current.getBoundingClientRect());
  };
  useEffect(() => {
    window.addEventListener("scroll", scrollHandler, true);
    return () => {
      window.removeEventListener("scroll", scrollHandler, true);
    };
  }, []);
  return (
    <div ref={inputRef} className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

Codesandbox(查看结果滚动,使用浏览器控制台代替codesandbox控制台)

9w11ddsr

9w11ddsr2#

如果在组件级别定义ref
像这样:

<SomeComponent ref={yourRef} />

您将从node属性获得getBoundingClientRect(),该属性来自组件上呈现的第一个元素

yourRef.current.node.getBoundingClientRect()

相关问题