React 如何通过类名获取指定div的高度并实现JQuery高度切换效果
实现方案
React中使用useRef获取DOM节点引用代替jQuery的选择器功能,offsetHeight属性可以读取元素的实际渲染高度,以下是完整实现代码:
import { useRef } from 'react'; import styles from './你的样式文件路径.module.css'; const YourComponent = () => { // 分别绑定coding和coding2两个DOM节点 const codingRef = useRef(null); const coding2Ref = useRef(null); const doSomething = () => { // 节点未挂载完成时直接返回避免报错 if (!codingRef.current || !coding2Ref.current) return; const codingHeight = codingRef.current.offsetHeight; if (codingHeight > 0) { codingRef.current.style.height = '0'; coding2Ref.current.style.height = '100%'; } else { codingRef.current.style.height = '50%'; coding2Ref.current.style.height = '49%'; } }; const ButtonDiv = () => ( <div ref={codingRef} className={styles.coding} > <button className={styles.codingButton} onClick={doSomething} > Click Me </button> </div> ); return ( <> <ButtonDiv /> {/* 给你的coding2 div添加ref绑定 */} <div ref={coding2Ref} className="coding2"> {/* coding2的页面内容 */} </div> </> ); }; export default YourComponent;
符合React数据流的优化写法(推荐)
你也可以通过状态管理高度,避免直接操作DOM样式,后续扩展更方便:
import { useRef, useState } from 'react'; import styles from './你的样式文件路径.module.css'; const YourComponent = () => { const codingRef = useRef(null); const [codingHeight, setCodingHeight] = useState('50%'); const [coding2Height, setCoding2Height] = useState('49%'); const doSomething = () => { if (!codingRef.current) return; const currentHeight = codingRef.current.offsetHeight; if (currentHeight > 0) { setCodingHeight('0'); setCoding2Height('100%'); } else { setCodingHeight('50%'); setCoding2Height('49%'); } }; const ButtonDiv = () => ( <div ref={codingRef} className={styles.coding} style={{ height: codingHeight }} > <button className={styles.codingButton} onClick={doSomething} > Click Me </button> </div> ); return ( <> <ButtonDiv /> <div className="coding2" style={{ height: coding2Height }}> {/* coding2的页面内容 */} </div> </> ); };
内容的提问来源于stack exchange,提问作者coder
相关产品推荐
相关产品推荐

