您好,我有一个如下所示的类组件:
class SomeComponent extends Component {
componentDidMount = () => {
const divElement = document.getElementbyId('id'); // this element could take a few seconds to load
if (props.something1 && props.something2) {
..do something with divElement's width
}
}
render() {
return ....
}
}我想等到加载了divElement,或者在加载divElement时触发一个事件,这样我以后就可以进行计算了。我尝试添加了setTimeout,但没有起作用
发布于 2020-08-21 16:56:06
这是一个愚蠢的解决方案,但它完成了自己的工作:
const getElementByIdAsync = id => new Promise(resolve => {
const getElement = () => {
const element = document.getElementById(id);
if(element) {
resolve(element);
} else {
requestAnimationFrame(getElement);
}
};
getElement();
});要使用它:
componentDidMount = async () => {
const divElement = await getElementByIdAsync('id');
if (props.something1 && props.something2) {
// ..do something with divElement's width
}
}https://stackoverflow.com/questions/63519548
复制相似问题