javascript - 使用 useRef 获取更改的孩子的更新高度
问题描述
我有一个手风琴组件,我使用 useRef 来测量孩子的身高。但是我对孩子有更改内容的功能,但孩子的测量没有更新,除非我再次点击切换。
const Accordian = ({ isOpen, children }) => {
const chilRef = useRef();
const [childHeight, setChildHeight] = useState(0);
useEffect(() => {
if (isOpen) {
const childHeight = chilRef.current && chilRef.current.scrollHeight;
setChildHeight(childHeight);
}
}, [isOpen]);
return (
<div
style={{
display: isOpen ? "block" : "none"
}}
>
<div ref={chilRef}>
{children}
<br />
<br />
<div>ChildHeight: {childHeight}</div>
</div>
</div>
);
};
export default function App() {
const [boxOpen, setBoxOpen] = useState(true);
const [expandChild, setExpandChild] = useState(false);
return (
<div className="App">
<button
onClick={() => {
setBoxOpen(prev => !prev);
}}
>
Toggle box
</button>
<Accordian isOpen={boxOpen}>
{expandChild ? (
<>
<h1>Hello CodeSandbox</h1>
<div>This has more content</div>
<div>More content......</div>
</>
) : (
<>
<div>Hello</div>
<button
onClick={() => {
setExpandChild(true);
}}
>
Expand child
</button>
</>
)}
</Accordian>
</div>
);
}
https://codesandbox.io/s/jovial-rgb-vcqnz?file=/src/App.js:83-1435
每次孩子改变时,我如何获得孩子的身高?
解决方案
只需将孩子传递给钩子的依赖项。
const Accordian = ({ children }) => {
const chilRef = useRef();
const [childHeight, setChildHeight] = useState(0);
useEffect(() => {
if (children) {
const childHeight = chilRef.current && chilRef.current.scrollHeight;
setChildHeight(childHeight);
}
}, [children]);
return (
<div>
<div ref={chilRef}>
{children}
<br />
<br />
<div>ChildHeight: {childHeight}</div>
</div>
</div>
);
};
推荐阅读
- javascript - 保存复选框选择
- java - 如何将 java.util.stream.Stream 写入 StreamingResponseBody 输出流
- java - 从字节数组到图像java
- javascript - 使用 dynmac setInterval 反应 UseEffect
- c++ - 为什么 map.find 使用 < 运算符而不是 == 运算符?
- javascript - 不占空间的置顶
- java - 具有动态方法名称的接口
- pandas - pandas 为小于 0.05 的值添加一个“*”
- html - 如何在 CSS 中调用 id 内的锚点?
- python - 列名未在熊猫数据框中引用