我有一个tabBarNavigation,我有一个Home组件。在“家庭”组件中,我希望能够在两个不同的屏幕之间导航。我有一个名为ReadButton的组件,当按下该组件时,它将带我进入另一个名为“ BookScreen”的屏幕。现在我已经写好了,所以我的HomeStack组件有两个屏幕“ HomeScreen”和“ BookScreen”。我的问题是按下时我无法使“ ReadButton”导航到“ BookScreen”。它说:“未定义不是对象(评估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);
现在,我尝试将“ Book:BookScreen”放到“ Home:HomeScreen”上,然后屏幕实际显示出来,但我无法在它们之间导航。我想念什么?
答案 0 :(得分:0)
请注意,HomeScreen或BookScreen内部的组件将不会获得导航道具。
1。您可以这样手动发送
<ReadButton navigation={this.props.navigation}/>
或
2。像这样在反应导航中使用内置的withNavigation
import {withNavigation} from 'react-navigation'
const ReadButton=(props)=>{}//Now you can access navigation prop here
export default withNavigation(ReadButton)
当您的组件被深度嵌套并且您想访问导航道具而无需手动传递道具时,第二种方法将派上用场。
答案 1 :(得分:0)
也许您可以尝试使用钩子?
yarn add react-navigation-hooks@alpha
import { useNavigation } from 'react-navigation-hooks'
export default function Screen1 () {
const { navigate } = useNavigation()
return (
<Button
title='Try'
onPress={() => { navigate('Screen2') }}
/>
)
}