簡體   English   中英

如何在 React 中將 dom 元素從子組件移動到父組件?

[英]How to move a dom element from a child component to a parent component in React?

我有兩個組件,一個父母和一個孩子。

父組件

const Parent = () => {
return (
<>
<div className="container"></div>
<div>more content</div>
<Child/>
</>
)
}

子組件

const Child = () => {

const importantFunctionMustBeInChild = () => {
//Does a bunch of stuff that can't be done in the parent due to a lot of state that doesn't make sense to have in the parent
}

return (
<>
<button onClick={importantFunctionMustBeInChild}>Important Button</button>
</>
)
}

問題是我在子組件中有一個按鈕。 此按鈕根據許多不同的 state 切換有條件地呈現,並且具有不能在父組件中的功能,因為將其放在那里沒有意義,並且需要很長時間才能移動所有 state 和功能。

問題是我現在需要將按鈕指向container div 在父組件中的位置。 有什么辦法可以做到這一點?

按照邏輯,你可以在子組件中為父組件的 state 分配一個值(字符串,object,數組),對吧? 那么為什么不能將 function 分配給 state 並在父項中單擊時運行它?

您可以明確地,在您的孩子中,指定 function 作為對父母 state 的引用,僅此而已!

useEffect(() => {
    // assign, don't invoke the function yet!
    setFunctionToExecute(() => importantFunctionMustBeInChild);
}, []);

這是一個完整的工作演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM