我有一個像這樣的功能反應組件:
function ComponentA(){
function AddComponentB(){
return <><ComponentB /></>
}
useEffect(() => {
AddComponentB();
}, []);
return
<>
<div id="parent"></div>
</>
}
現在我明白了,useEffect一旦加載,下面的所有內容都會ComponentA被加載。我想將ComponentBid添加到 div 中parent。請幫助我了解如何指定添加組件的位置。
PS我知道我可以做到,document.getElementById("parent").append(ComponentB)但我正在尋找其他方法。
uj5u.com熱心網友回復:
不,您在使用 React 時不直接操作 DOM。
您需要有一個“標志”來指示是否要渲染額外的組件。
就像是
function ComponentA(){
const [renderComponentB, setRenderComponentB] = useState(false);
useEffect(() => {
setRenderComponentB(true);
}, []);
return (
<>
<div id="parent">
{renderComponentB && <ComponentB/>}
</div>
</>
);
}
雖然我不確定為什么要延遲ComponentB一個渲染周期。
至于getBoundingClientRectof ComponentA,沒有這樣的事情,因為這取決于組件在 DOM 中實際呈現的內容。ComponentA它本身不是 DOM 的一部分。
在您的特定情況下,盡管您可以ref向#parent元素添加 a并將其用于getBoundingClientRect,因為它是您的“容器”元素ComponentA
function ComponentA(){ const [renderComponentB, setRenderComponentB] = useState(false); const parentRef = useRef();
useEffect(() => {
setRenderComponentB(true);
}, []);
useLayoutEffect(() => {
const rect = parentRef.current.getBoundingClientRect();
// do what you want with the rect here
// if you want to apply values to the ComponentB
// add them to a state variable and use those when
// rendering the ComponentB
}, [])
return (
<>
<div id="parent" ref={parentRef}>
{renderComponentB && <ComponentB/>}
</div>
</>
);
}
uj5u.com熱心網友回復:
嘗試使用conditional rendering,如下所示:
export default function ComponentA() {
const [renderComponentB, setRenderComponentB] = useState(false)
useEffect(() => {
setRenderComponentB(true);
}, []);
return(<div id="parent">
{renderComponentB && <ComponentB/>}
</div>)
}
uj5u.com熱心網友回復:
您應該呼叫在渲染中回傳組件的方法。正如我從您的回答中所理解的那樣,您不需要 useEffect 。
function ComponentA(){
function AddComponentB(){
return <><ComponentB /></>
}
return
<>
<div id="parent">
{AddComponentB()}
</div>
</>
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/394566.html
標籤:javascript 反应 反应功能组件
