我有一個用箭頭函式表示法宣告的 React 組件。這個組件有一個子組件,它應該改變 ParentComponent 的狀態。我怎樣才能做到這一點?如果我們將狀態更改作為函式(在本例中為 changeState)傳遞,它會是什么樣子?
const ParentComponent = () => {
const [myState, setMyState] = useState(false);
const changeState = () => setMyState(!myState);
return(
<ChildComponent /> // pass the state variables
);
}
const ChildComponent = () => { // receive the state variables
// change state of parent component
}
uj5u.com熱心網友回復:
要將狀態更改傳遞給子類,您只需將函式作為屬性傳遞給子類。這適用于任何函式,setMyState如果你想進入子函式,你甚至可以傳入
const ParentComponent = () => {
const [myState, setMyState] = useState(false);
const changeState = () => setMyState(!myState);
return(
<ChildComponent
changeState={changeState}
/> // pass the state variables
);
}
const ChildComponent = ({changeState}) => { // receive the state variables
// change state of parent component
// you can use changeState here and
// it will update the parent component and rerender the page
}
uj5u.com熱心網友回復:
您也可以將函式作為道具傳遞給子組件。嘗試像這樣將 changeState 函式傳遞給子組件
const ParentComponent = () => {
const [myState, setMyState] = useState(false);
const changeState = () => setMyState(!myState);
return(
<ChildComponent handleChange={changeState} /> // pass the state variables
);
}
const ChildComponent = ({handleChange}) => { // receive the state variables
// change state of parent component by simply calling
// handleChange as a normal function
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/352869.html
上一篇:具有固定位置和css屬性“animation”的div,當我動態添加類時,它不會使用“transform:translateY(0%)”屬性進行影片處理
