React-navigation v5:将函数作为参数传递给headerRight按钮。

问题描述 投票:0回答:1

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

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.Canot read property '_confirmClick' of typeError: 无法读取未定义的属性'_confirmClick'。

react-native react-hooks react-navigation
1个回答
3
投票

你不需要在header上设置参数,你可以直接将该方法传递给header。你不需要在header上设置参数,你可以直接将该方法传递给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
}

在这里,你可以直接将该方法传递给headerRight:这里 是一些文件。

© www.soinside.com 2019 - 2024. All rights reserved.