![](/img/trans.png)
[英]React native. How to pass state from component to BottomTab.Screen?
[英]How to pass state from component to main screen in react-native
我无法将 state 从组件传递到 react-native 中的主屏幕
例如
主屏幕.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 组件中更改 state 时,如何让 adCreated 的 state 在 MainScreen 上显示为true
。
谢谢,
阿纳夫
为此,您需要提升 state如果您的用例不包含这些项目的映射,只需在主要组件中声明 state 并将其作为道具传递给孩子。
编辑:
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>
)
}
根据您的要求,您可以在尝试完成此操作时遵循此类行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.