我是个新手。我需要帮助获取coding
分区的高度。下面是我正在使用的react代码作为示例:
const buttonDiv = () => (
<div
className={styles.coding}
>
<button
className={styles.codingButton}
onClick={() => doSomething()}
>
Click Me
</button>
</div>
);
因此,假设styles.coding
类为coding
,styles.codingButton
为coding-button
。然后还有另一个div,它的类是let,比如coding2
例如,我如何使用react来检查和查看在coding
分区上设置的高度。实际上,我要做的是将这个jquery转换为react
function dosomething() {
if($('.coding').height() > 0){
$('.coding').height('0')
$('.coding2').height('100%')
}
else {
$('.coding').height('50%')
$('.coding2').height('49%')
}
}
发布于 2021-07-24 11:30:42
如上所述,尝试利用ref
来获得您想要的东西。这里有个小东西也许能帮到你。要查看它的工作情况,您可以在这里查看它,并使用您的控制台检查日志。https://codepen.io/justdan/pen/zYwPWjp?editors=1010
const { useRef, useEffect } = React;
const ButtonDiv = () => {
const div = useRef(null);
function doSomething() {
const height = div.current.offsetHeight;
console.log('height', height);
if (height > 0) {
console.log('hit');
};
};
return (
<div
ref={div}
className={'coding'}
>
<button
className={'codingButton'}
onClick={() => doSomething()}
>
Click Me
</button>
</div>
);
};
ReactDOM.render(<ButtonDiv />, document.getElementById('app'));
发布于 2021-07-24 11:11:13
对于没有使用jQuery的注释,我更喜欢使用window.getComputedStyle()
方法,并将ref作为参数传递给div。https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
https://stackoverflow.com/questions/68506579
复制相似问题