【问题标题】:React-navigation v5 : Pass function as parameter to be used in headerRight buttonReact-navigation v5:将函数作为参数传递给 headerRight 按钮
【发布时间】:2020-05-05 05:29:32
【问题描述】:

我试图在 headerRight 按钮单击屏幕上调用函数。 我在 useEffect 中将 func 作为参数传递,如下所示。

useEffect(() => {

    navigation.setParams({ _confirmClick: confirmNotification })

  }, [navigation])
    useLayoutEffect(() => {
        navigation.setOptions({
          headerRight: () => (
            <TouchableOpacity
              onPress={() => params._confirmClick('New') }
              style={[theme.marginRight15]}>
              <View style={[styles.sendNotificationButton,
              {
                backgroundColor: notification ? theme.colors.notificationDeleteButtonColor :
                  theme.colors.sendbuttonColor,
                borderColor: notification ? theme.colors.notificationDeleteButtonColor :
                  theme.colors.sendbuttonColor,
              }]}>
                <Ionicons name="ios-send" size={15}
                  style={theme.padding3}
                  color={theme.colors.whiteColor} />
              </View>
            </TouchableOpacity>
          ),
        });
      }, [navigation]);



  function confirmNotification(status) {
...
}

当我点击按钮时,它显示:TypeError: Cannot read property '_confirmClick' of undefined

【问题讨论】:

    标签: react-native react-hooks react-navigation


    【解决方案1】:

    您不需要在标题上设置参数。您可以直接将该方法传递给 headerRight :

    function yourScreenName({ navigation }) {
      useLayoutEffect(() => {
        navigation.setOptions({
          headerRight: () => (
            <TouchableOpacity
              onPress={() => confirmNotification('New')}
              style={[theme.marginRight15]}>
              <View style={[styles.sendNotificationButton,
              {
                backgroundColor: notification ? theme.colors.notificationDeleteButtonColor :
                  theme.colors.sendbuttonColor,
                borderColor: notification ? theme.colors.notificationDeleteButtonColor :
                  theme.colors.sendbuttonColor,
              }]}>
                <Ionicons name="ios-send" size={15}
                  style={theme.padding3}
                  color={theme.colors.whiteColor} />
              </View>
            </TouchableOpacity>
          ),
        });
      }, [navigation, confirmNotification]); // pass method directly here
    }
    

    Here 是一些文档。

    【讨论】:

    • 我尝试了很多东西,除了在第二个参数中传递确认通知。你能解释一下为什么我需要通过 confirmNotification 吗?
    猜你喜欢
    • 1970-01-01
    • 2020-05-23
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多