use*_*531 5 reactjs office-ui-fabric
我有一个组件,并且要在鼠标悬停在“ Persona”元素上时使用Office-UI-Fabric-react组件“ Callout”。
如果我引用包含“ Persona”元素
(使用ref={this.setPersonaRef})的“ div”,则“标注”有效,
但componentRef={this.setPersonaRef}在“ Persona”元素中导致
CalloutContent.componentDidMount()中的异常:TypeError:element.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>;
}
}
Run Code Online (Sandbox Code Playgroud)
如何解决该异常?
Ran*_*all 17
由于使用getBoundingClientRect或其他类似的方法,你需要点current财产ref。
从文档:
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>
);
}
Run Code Online (Sandbox Code Playgroud)
工作Codesandbox(使用浏览器控制台显示结果滚动而不是 Codesandbox 控制台)
| 归档时间: |
|
| 查看次数: |
1874 次 |
| 最近记录: |