如何从函数组件导航到另一个屏幕



我有一个选项卡导航,我有一个主页组件。在主页组件中,我希望能够在两个不同的屏幕之间导航。我有一个名为ReadButton的组件,当按下它时,应该将我带到另一个名为"BookScreen"的屏幕。现在我已经写了,所以我的HomeStack组件有两个屏幕"主屏幕"和"书屏"。我的问题是我无法在按下时使"阅读按钮"导航到"书屏"。它说"未定义不是一个对象(评估 props.navigation.navigate(。

...//This is in the main class provided by react
const HomeStack = createStackNavigator(
  {
    Home: HomeScreen,
    Book: BookScreen,
  },
  config
);
const tabNavigator = createBottomTabNavigator({
HomeStack,
LinksStack,
SettingsStack,
});
tabNavigator.path = '';
export default tabNavigator;
...
//Below is the ReadButton class in a seperate file
import {withNavigation} from 'react-navigation'
const ReadButton = (props) => {

  const [ReadPressed, setReadPressed] = useState(true)
  const {navigate} = props.navigation.navigate
  if(ReadPressed){
    return(
            <View>
              <TouchableOpacity style={styles.buttonstyle} onPress={navigate("Home")}>
                <Text style={styles.textstyle}> READ </Text>
              </TouchableOpacity> 
            </View>  
    )
    }
    else {
        return(
            props.book
        )
    }
}

// Another class where i have my <ReadButton>
function BookCover(){
  <TouchableOpacity style={styles.bottomFlexItemWhenClicked} onPress= . 
  {() => setBookCoverState(true)}>
           <Text style={styles.BackgroundText}>{props.text}</Text>
           <ReadButton book={props.book} navigation={props.navigation}>   
          </ReadButton>
   </TouchableOpacity>)}
   }
    export default withNavigation(ReadButton);

现在我尝试将"书籍:书籍屏幕"放在"主页:主屏幕"上,然后屏幕实际显示,但我无法在它们之间导航。我错过了什么?

也许你可以试试钩子?

  1. 安装挂钩:yarn add react-navigation-hooks@alpha
  2. 然后在函数组件中使用它:
import { useNavigation } from 'react-navigation-hooks'
export default function Screen1 () {
  const { navigate } = useNavigation()
  return (
    <Button
      title='Try'
      onPress={() => { navigate('Screen2') }}
    />
  )
}

请注意,主屏幕或书屏内的组件不会收到导航道具。

1.要么像这样手动发送它们

<ReadButton navigation={this.props.navigation}/>

2.像这样

使用内置的带有导航的反应导航
import {withNavigation} from 'react-navigation'
const ReadButton=(props)=>{}//Now you can access navigation prop here
export default withNavigation(ReadButton)

当您的组件深度嵌套并且您希望在不手动传递 props 的情况下访问导航道具时,第二种方法将派上用场。

相关内容

  • 没有找到相关文章

最新更新