我正在Chrome上使用React 15,并希望连接一个事件侦听器以检测对父容器的更改。在寻找选项之后,我遇到了ResizeObserver,不确定如何在我的项目中使用它。
当前,我将其放入我的构造函数中,但它似乎不打印任何文本,并且不确定在observe
调用中应放入什么。
class MyComponent extends React.Component {
constructor(props) {
super(props);
const resizeObserver = new ResizeObserver((entries) => {
console.log("Hello World");
});
resizeObserver.observe(somethingGoesHere);
}
render() {
return (
<AnotherComponent>
<YetAnotherComponent>
</YetAnotherComponent>
<CanYouBelieveIt>
</CanYouBelieveIt>
<RealComponent />
</AnotherComponent>
);
}
}
理想情况下,我也不想将RealComponent
包裹在div
中并给div
赋予一个ID。有没有办法直接RealComponent
?
我的目标是观察RealComponent
的任何大小更改,但MyComponent
也可以。我应该在somethingGoesHere
插槽中放什么?
编辑:
为了工作,我咬了一下子弹,并在div
周围包裹了一个RealComponent
标签。然后,我给它一个ID <div id="myDivTag">
,并更改了observe
调用:
resizeObserver.observe(document.getElementById("myDivTag"));
但是,运行此命令时,我得到:
未捕获的TypeError:resizeObserver.observe不是函数
任何帮助将不胜感激。
答案 0 :(得分:3)
ComponentDidMount
是设置观察者的最佳位置,但您也想断开ComponentWillUnmount
的连接。
class MyComponent extends React.Component {
resizeObserver = null;
resizeElement = createRef();
componentDidMount() {
this.resizeObserver = new ResizeObserver((entries) => {
// do things
});
this.resizeObserver.observe(this.resizeElement.current);
}
componentWillUnmount() {
if (this.resizeObserver) {
this.resizeObserver.disconnect();
}
}
render() {
return (
<div ref={this.resizeElement}>
...
</div>
);
}
}
答案 1 :(得分:2)
ResizeObserver不能进入构造函数,因为在组件生命周期中的那个时刻div不存在。
我认为您无法绕开多余的div,因为无论如何React组件都会减少为html元素。
将其放在componentDidMount中,它应该可以工作:
componentDidMount() {
const resizeObserver = new ResizeObserver((entries) => {
console.log("Hello World");
});
resizeObserver.observe(document.getElementById("myDivTag"));
}
答案 2 :(得分:1)
我最近正在解决一个类似的问题,不同之处在于我的应用主要使用钩子和功能组件。
以下是如何在 React 功能组件中使用 ResizeObserver 的示例(在打字稿中):
function updateUserOrder(productId, action){
var url = '/updateItem/'