我想在类组件中使用navigation
,它不是屏幕组件,并且不能通过navigation
自动访问props
,所以我必须将导航传递给它props
。但是父组件是功能组件,我在其中使用了navigation
钩子。
但是,如何在子组件中使用navigation
?
ParentComponent.js
import React from 'react';
import {View , TouchableOpacity} from 'react-native';
import {useNavigation} from 'react-navigation-hooks';
import ChildComponent from './ChildComponent';
const ParentComponent =()=>{
const {navigate} = useNavigation();
return(
<View>
<TouchableOpacity onPress={() => navigate('AnotherScreen')} />
<ChildComponent />
</View>
)
}
export default ParentComponent;
ChildComponent.js
import React , {Component} from 'react';
import {View , TouchableOpacity} from 'react-native';
class ChildComponent extends Component {
render(){
return(
<View>
<TouchableOpacity onPress={() => ???}>
<Text>sample text</Text>
</TouchableOpacity>
</View>
)
}
}
export default ChildComponent;
我使用以下依赖项:
"dependencies": {
"@react-native-community/masked-view": "^0.1.10",
"native-base": "2.13.8",
"react": "16.13.1",
"react-native": "0.63.0",
"react-native-gesture-handler": "^1.6.1",
"react-navigation": "^4.0.7",
"react-navigation-drawer": "^2.3.3",
"react-navigation-hooks": "^1.1.0",
"react-navigation-stack": "^1.8.1",
},
我们非常感谢您的指导。
答案 0 :(得分:1)
如果您有权访问父组件中的导航道具,只需使用道具将其传递给子导航。
const ParentComponent =()=>{
const {navigate} = useNavigation();
return(
<View>
<TouchableOpacity onPress={() => navigate('AnotherScreen')} />
<ChildComponent navigate={navigate}/>
</View>
)
}
class ChildComponent extends Component {
render(){
return(
<View>
<TouchableOpacity onPress={() => this.props.navigate('screenname')}>
<Text>sample text</Text>
</TouchableOpacity>
</View>
)
}
}
答案 1 :(得分:0)
您必须在父组件的道具内部进行导航。
在父组件中:
const ParentComponent =(props)=>{
const {navigate} = useNavigation();
return(
<View>
<TouchableOpacity onPress={() => navigate('AnotherScreen')} />
<ChildComponent navigation={props.navigation} />
</View>
)
}
在子组件中,您可以访问导航:
class ChildComponent extends Component {
constructor(props) {
super(props);
}
render() {
return (
<View>
<TouchableOpacity onPress={() => this.props.navigation.navigate('SomeOtherScreen')}>
<Text>sample text</Text>
</TouchableOpacity>
</View>
)
}
}