我想知道在类组件中设置参数和响应本地导航的选项的最佳方法。注意,在选项中使用相同的参数。当我将所有代码放入构造函数中时,由于时间问题,我得到了params undefined
。而且起作用了。对于我来说,当我在componentDidMount
中添加选项时,我将在下面的代码中编写一些示例。
1-使用类组件的第一种情况(它正在工作)
type Props = {
navigation: NavigationProp<any>;
route: RouteProps<{ Example: {title: string} }, 'Example'>
}
export default class Example extends Component <Props> {
constructor(props: Props){
super(props)
this.props.navigation.setParams({ title: 'title' });
}
componentDidMount(){
this.props.navigation.setOptions({ title: this.props.route.params.title })
}
...
}
使用FC的第二个例子:(不使用这个例子,但我认为这也是FC最好的方法)。
export function Example: React.FC = () => {
const navigation = useNavigation();
const route = useRoute();
useLayoutEffect(()=>{
navigation.setParams({ title: 'title' });
navigation.setOptions({ title: route.params.title })
})
...
}
因此,我希望我的问题是明确的,是否有正确的方式来设置标题选项与lates导航上的反应本地?
发布于 2022-04-23 01:07:34
构造函数是组件生命周期中的第一步,您将在其中设置参数,这意味着将更新一个支柱。因此,我们需要一个函数来理解状态或接收到的道具上的每个更新,并且监听器除了"componentDidUpdate(){}“之外什么都不是:
import {NavigationProp, RouteProp} from '@react-navigation/native';
import React, {Component} from 'react';
import {Text, StyleSheet, View} from 'react-native';
type Props = {
navigation: NavigationProp<any>;
route: RouteProp<{Example: {title: string}}, 'Example'>;
};
export default class Example extends Component<Props> {
constructor(props: Props) {
super(props);
this.props.navigation.setParams({title: 'title'});
}
componentDidUpdate() {
this.props.navigation.setOptions({title: this.props.route.params.title});
}
render() {
return (
<View style={styles.container}>
<Text style={styles.textStyle}>Use component did update :)</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
padding: 30,
},
textStyle: {
color: 'black',
fontSize: 20,
fontWeight: 'bold',
},
});
https://stackoverflow.com/questions/71976057
复制