我有一个accordian组件,我使用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
我怎么才能让孩子每次改变时都长高呢?
发布于 2020-05-02 20:47:08
您的逻辑错误...第一次切换没有更改isOpen
的值,因此为useEffect never run
。一旦你更改为false,它就会re-run useEffect
。
您必须移动以扩展子组件中的逻辑。或use forwarRef
来计算height in parent
。
日志:
Before: useEffecttrue 0
Before: useEffecttrue 0
Inside: useEffecttrue 73
Before: useEffecttrue 73
Before: useEffecttrue 73
expend...
Before: useEffecttrue 73
Before: useEffecttrue 73
toggle::...
Before: useEffectfalse 73
Before: useEffectfalse 73
Inside: useEffectfalse 0
Before: useEffectfalse 0
Before: useEffectfalse 0
示例解决方案: https://codesandbox.io/s/awesome-allen-evmhb?file=/src/App.js:0-1515
发布于 2020-05-03 12:10:26
只需将子对象传递给钩子的依赖项即可。
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>
);
};
https://stackoverflow.com/questions/61559117
复制相似问题