[英]Passing variable from header to screen in React Native
對於我的學習,我正在研究一個反應原生項目,但我被困住了。
我的結構如下:
MyApp
- Components (folder)
-+ Header.js
-+ Navigationbar.js
- Screens (folder)
-+ Home.js
Header.js 如下所示:
export default function HeaderComponent() {
const [
selectedIndex,
setSelectedIndex
] = React.useState(0);
return (
<View>
<View style={style.header}>
<Image //logo extracted from '../assets/logo.png'
source={require('../assets/logo.png')}
style={style.image}/>
<SearchBar //searchbar to search with the required props
platform='default'
containerStyle={style.searchbar}
inputContainerStyle={style.searchbarInput}
inputStyle={style.inputText}
placeholder="Search here..."
lightTheme
round
/>
</View>
<View style={style.threeButtons}>
<ButtonGroup
containerStyle= {style.buttonContainer}
buttonStyle={{ width: 60 }}
buttonContainerStyle={style.buttonContainerStyle}
textStyle={style.textStyle}
selectedTextStyle={style.textStyle}
innerBorderStyle={{color: '#EBEBEB'}}
buttons={[
"A-Z",
"Highest",
"Sport",
]}
onPress={selectedIdx =>
setSelectedIndex(selectedIdx)
}
selectedButtonStyle={style.selectedButtonStyle}
selectedIndex={selectedIndex}
/>
</View>
</View>
);
}
Home.js 文件如下所示:
export default function Home() {
return (
//this 'SafeAreaView' is required to render it safe on the screen, within the margins
<SafeAreaView style={style.container}>
<HeaderComponent/>
</SafeAreaView>
);
}
我想將 Header.js 中的 selectedIndex 傳遞給 Home.js,這樣我就可以根據選擇的選項卡(0、1 或 2)呈現文本 我該怎么做? 這是正確的方法嗎,但我錯過了什么。 還是我必須做不同的事情?
由於 Home.js 和 HeaderComponent 具有父子關系,您可以通過“將 state 向上提升”來實現您想要的。 即,而不是在 HeaderComponent 中使用 useState,您可以在 Home 中使用它並將 setSelectedIndex fn 作為參數傳遞給 HeaderComponent。
export default function Home() {
const [
selectedIndex,
setSelectedIndex
] = React.useState(0);
return (
<SafeAreaView style={style.container}>
<HeaderComponent selectedIndex={selectedIndex} setSelectedIndex={setSelectedIndex}/>
</SafeAreaView>
);
}
export default function HeaderComponent({selectedIndex,
setSelectedIndex}) {
return (
{/* Your existing code */}
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.