我在 react-native 中將狀態從組件傳遞到主螢屏時遇到問題
例如
MainScreen.js
const MainScreen = () => {
return (
<>
<AdButton/>
<Text>{adCreated}</Text>
</>
)
}
AdButton.js
const [adCreated, createAd] = useState(false);
const adButton = () => {
createAd(true);
}
const AdButton = () => {
return (
<TouchableOpacity onPress={adButton}>Create an Ad</TouchableOpacity>
)
}
當 AdButton 組件中的狀態發生更改時,如何true在 MainScreen 上顯示 adCreated 的狀態。
謝謝,
阿納夫
uj5u.com熱心網友回復:
為此,您需要提升狀態如果您的用例不包含這些專案的映射,只需在主組件中宣告狀態并將其作為道具傳遞給子組件。
編輯:
const MainScreen = () => {
const [adCreated, createdAd] = useState(false);
return (
<>
<AdButton createdAd={createdAd}/>
<Text>{adCreated}</Text>
</>
)
}
const AdButton = ({createdAd}) => {
return (
<TouchableOpacity onPress={createdAd((prev) => !prev)}>Create an Ad</TouchableOpacity>
)
}
根據您的要求,您可以在嘗試完成此操作時遵循此類行為。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/466401.html
標籤:javascript 反应 反应式
