首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >在设置使用setParams的导航选项之前,使用setOptions进行导航的最佳方法是什么?

在设置使用setParams的导航选项之前,使用setOptions进行导航的最佳方法是什么?
EN

Stack Overflow用户
提问于 2022-04-23 01:09:55
回答 1查看 287关注 0票数 0

我想知道在类组件中设置参数和响应本地导航的选项的最佳方法。注意,在选项中使用相同的参数。当我将所有代码放入构造函数中时,由于时间问题,我得到了params undefined。而且起作用了。对于我来说,当我在componentDidMount中添加选项时,我将在下面的代码中编写一些示例。

1-使用类组件的第一种情况(它正在工作)

代码语言:javascript
代码运行次数:0
运行
复制
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最好的方法)。

代码语言:javascript
代码运行次数:0
运行
复制
export function Example: React.FC = () => {
const navigation = useNavigation();
const route = useRoute();

useLayoutEffect(()=>{
navigation.setParams({ title: 'title' });
navigation.setOptions({ title: route.params.title })
})

...
}

因此,我希望我的问题是明确的,是否有正确的方式来设置标题选项与lates导航上的反应本地?

EN

回答 1

Stack Overflow用户

发布于 2022-04-23 09:07:34

构造函数是组件生命周期中的第一步,您将在其中设置参数,这意味着将更新一个支柱。因此,我们需要一个函数来理解状态或接收到的道具上的每个更新,并且监听器除了"componentDidUpdate(){}“之外什么都不是:

代码语言:javascript
代码运行次数:0
运行
复制
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',
  },
});

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71976057

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档