将变量从 header 传递到 React Native 中的屏幕

Passing variable from header to screen in React Native

为了学习,我正在做一个 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>
  );
}

我想将 selectedIndex 从 Header.js 传递到 Home.js,这样我就可以根据所选的选项卡(0、1 或 2)呈现文本 我该怎么做呢?这是正确的方法吗,但我错过了什么吗?还是我必须做不同的事情?

由于Home.js 和HeaderComponent 具有父子关系,您可以通过“提升状态”来实现您想要的。也就是说,与其在 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   */}

 )
}