在反應中,有一個組件 A 里面有一個組件 BI 使用過。還有一個組件 C,在 C 內部有一個按鈕,當單擊它時,它會從組件 A 中隱藏組件 B。我怎樣才能實作此功能
uj5u.com熱心網友回復:
僅使用 React,您可以通過以下方式實作:
- 所有這些組件的父/根組件都有一個布爾狀態,我們稱之為
showComponentB. 它被初始化為true. - 這個根組件將狀態
showComponentB作為 props 傳遞給組件 A。在組件 A 中,它用于顯示組件 B(如果showComponentB是)true或隱藏(如果是)false。 - 根組件傳遞一個函式來改變
showComponentB組件 C 的狀態,并在單擊按鈕時呼叫。 - 的狀態
showComponentB在根中更新為false,更新后的值傳遞給組件 A 并隱藏組件 B。
uj5u.com熱心網友回復:
你可以嘗試這樣的事情。希望它可以幫助你。
import { useState } from "react";
import "./styles.css";
export default function App() {
const [isVisible, setIsVisible] = useState(true)
return (
<div className="App">
<CompA>
{isVisible && <CompB>
<CompC clickHandler={()=>setIsVisible(false)}/>
</CompB> }
</CompA>
</div>
);
}
export const CompA = (props) => {
return <>
<div style={{backgroundColor:'red', height:'200px',width:'200px'}}>Component A
{props.children}
</div>
</>}
export const CompB = (props) => {
return <>
<div style={{backgroundColor:'blue', height:'150px',width:'150px'}}>Component B
{props.children}
</div>
</>
}
export const CompC = (props) => {
return <>
<div style={{backgroundColor:'green', height:'100px',width:'100px'}}>Component C
<button onClick={props.clickHandler}>hide B</button>
</div>
</>
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/522742.html
標籤:反应dom路线
