我正在使用一个类组件,我想从这里导航到另一个屏幕。但它表示,导航尚未定义。我查阅了文档,意识到我需要使用userNavigation
This。但我不知道如何实际使用它。有人帮忙请
export default class ReduxScreen extends Component {
render() {
return (
<View>
<Button block style={{ marginHorizontal: 30, marginTop: 50 }} onPress={() => {
//I want to add the useNavigation here
}}>
<Text style={{ color: '#FFF' }}>Start</Text>
</Button>
</View>
)
}}
useNavigation
是一个钩子,钩子只能在这样的功能组件中使用。
const navigation = useNavigation()
但是,当您使用类组件时,您可以像这样导航。
this.props.navigation.navigate('YouScreen', {paramsIfAny})
在类组件中放入But you have to make sure that navigation prop is available
。如果console.log
可用,则上面的行将起作用。如果不可用,则必须遵循此操作。
注:navigation prop is always available in the parent route(Route which is used to navigate some screen)
https://reactnavigation.org/docs/navigating-without-navigation-prop
另一个解决方案是,您可以将导航道具从功能组件传递到这样的类组件。
export default function RootFunction (){
const navigation = useNavigation() // extract navigation prop here
return <ReduxScreen navigation={navigation} /> //pass to your component.
}
class ReduxScreen extends Component {
render () {
return (
<View>
<Button block style={{ marginHorizontal: 30, marginTop: 50}}
onPress={() => {
this.props.navigation.navigate('YourScreen')
// now prop will be available here
}}>
<Text style={{ color: '#FFF' }}>Start</Text>
</Button>
</View>
)
}
}
适用于那些正在与路由v6及更多路由作斗争的人。您必须在组件类之外定义一个函数,并按如下方式使用它:
function myParams(Component) {
return props => <Component navHook={useNavigate()} />;
}
在您的课堂组件中:
this.props.navHook('/SomeWhere')
请记住,您已经将类封装在函数中:
export default myParams(Card);
对于那些在TypeScript和@vahid-sabet的提议中挣扎的人:
export type NavComponentProps<T extends Readonly<unknown>> =
T & { navigate: NavigateFunction; };
export class NavComponent<T extends Readonly<unknown>>
extends React.PureComponent<NavComponentProps<T>> { };
export function navHOC<T extends Readonly<unknown>>
(Component: typeof NavComponent<T>) {
return (props: T) => <Component {...props} navigate={useNavigate()} />;
}
然后申报你的班级:
class _MyClass extends NavComponent<MyProps> {
constructor(props: NavComponentProps<MyProps>) {
super(props);
// I can call:
this.props.navigate();
}
};
export const MyClass = navHOC(_MyClass);
使用<Link />
代替blow
import { Link } from 'react-router-dom';
export default class ReduxScreen extends Component {
render() {
return (
<View>
<Button component={Link} to="some-where" block style={{ marginHorizontal: 30, marginTop: 50 }}
}}>
<Text style={{ color: '#FFF' }}>Start</Text>
</Button>
</View>
)
}}
如链接文档中所示,您必须使用functional
组件才能使用导航挂钩。
试试这个
import { useNavigation } from '@react-navigation/native';
export default () => {
const navigation = useNavigation();
return (
<View>
<Button
block
style={{ marginHorizontal: 30, marginTop: 50 }}
onPress={() => navigation.navigate('YourScreenHere')}
>
<Text style={{ color: '#FFF' }}>Start</Text>
</Button>
</View>
);
};
希望这能有所帮助!