gpt4 book ai didi

reactjs - 如何解决 "element.getBoundingClientRect is not a function"

转载 作者:行者123 更新时间:2023-12-03 13:38:17 25 4
gpt4 key购买 nike

我有一个组件,并且希望当鼠标悬停在“Persona”元素上时使用 Office-UI-Fabric-react 组件“Callout”。
如果我引用包含“Persona”元素的“div”,“Callout”就会起作用
(使用ref={this.setPersonaRef}),
但“Persona”元素中的 componentRef={this.setPersonaRef} 会导致

Exception in CalloutContent.componentDidMount(): TypeError:element.getBoundingClientRect is not a function

这是组件:

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>;
}
}

如何解决异常?

最佳答案

因为使用 getBoundingClientRect 或其他类似方法,您需要指向 refcurrent 属性。

来自文档:

useRef (or simple class ref) returns a mutable ref object whose.current property is initialized to the passed argument(initialValue). The returned object will persist for the full lifetimeof the component.

示例:

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控制台)

关于reactjs - 如何解决 "element.getBoundingClientRect is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51963089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com