当它的DOM元素(包括所有子节点)实际加载到页面上并准备就绪时,我想在我的react.js组件上调用一个回调。具体来说,我有两个想要渲染相同大小的组件,选择具有自然尺寸的任何一个组件的最大值。
看起来componentDidMount
并不是我真正想要的,因为每个组件仅被调用一次,但是我希望在组件完成渲染后再次调用我的回调。我以为可以将onLoad
事件添加到顶级DOM元素中,但是我想这仅适用于某些元素,例如<body>
和<img>
。
当它的DOM元素(包括所有子节点)实际加载到页面上并准备就绪时,我想在我的react.js组件上调用一个回调。具体来说,我有两个想要渲染相同大小的组件,选择具有自然尺寸的任何一个组件的最大值。
看起来componentDidMount
并不是我真正想要的,因为每个组件仅被调用一次,但是我希望在组件完成渲染后再次调用我的回调。我以为可以将onLoad
事件添加到顶级DOM元素中,但是我想这仅适用于某些元素,例如<body>
和<img>
。
Answers:
在componentDidMount中添加onload侦听器
class Comp1 extends React.Component {
constructor(props) {
super(props);
this.handleLoad = this.handleLoad.bind(this);
}
componentDidMount() {
window.addEventListener('load', this.handleLoad);
}
componentWillUnmount() {
window.removeEventListener('load', this.handleLoad)
}
handleLoad() {
$("myclass") // $ is available here
}
}
看起来像的组合componentDidMount
,并componentDidUpdate
会完成这项工作。当DOM可用时,第一个调用在初始渲染之后调用,一旦更新的DOM可用,则在任何后续渲染之后调用第二个调用。就我而言,我都让他们委托一个共同的职能来做同样的事情。
的组合componentDidMount
,并componentDidUpdate
会得到与类组件的代码完成任务。但是,如果您要使用全部功能组件编写代码,the Effect Hook
将会做得很好,它与componentDidMount
和相同componentDidUpdate
。
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
我将componentDidUpdate应用于表以使所有列都具有相同的高度。它与jquery中的$(window).load()相同。
例如:
componentDidUpdate: function() {
$(".tbl-tr").height($(".tbl-tr ").height());
}
componentDidUpdate
它没有被要求进行初始渲染,因此在更改道具或状态之前不会应用您的功能:reactjs.org/docs/react-component.html#componentdidupdate
我发现在这简单的包装代码componentDidMount
或componentDidUpdate
用setTimeout
用0毫秒的时间确保在执行以下操作之前,已使用React更改来更新浏览器DOM。setTimeout
的功能。
像这样:
componentDidMount() {
setTimeout(() => {
$("myclass") // $ is available here
}, 0)
}
这会将匿名函数放在JS事件队列中,以在当前运行的React堆栈框架完成后立即运行。
在现代浏览器中,它应该像
try() {
if (!$("#element").size()) {
window.requestAnimationFrame(try);
} else {
// do your stuff
}
};
componentDidMount(){
this.try();
}
下面是我想在DOM准备好后尝试使用document.getElementsByClassName获取类之前想到的。我从componentDidMount()生命周期方法中调用了此函数。
changeIcon() {
if (
document.getElementsByClassName('YOURCLASSNAME')
.length > 0 &&
document.getElementsByClassName('YOURCLASSNAME').length > 0
) {
document.getElementsByClassName(
'YOURCLASSNAME'
)[0].className = 'YOUR-NEW-CLASSNAME';
document.getElementsByClassName(
'YOUR-OTHER-EXISTING-CLASSNAME'
)[0].style.display = 'block';
} else {
setTimeout(this.changeIcon, 500);
}
}
componentWillUnmount() { window.removeEventListener('load', this.handleLoad) }