React-navigation v5 : Pass function as parameter to be used in headerRight button

╄→尐↘猪︶ㄣ 提交于 2020-05-20 10:51:09

问题


I ham trying to call function on headerRight button click on screen. I am passing func as param in useEffect as shown below.

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) {
...
}

When I click on button it says : TypeError: Cannot read property '_confirmClick' of undefined


回答1:


You don't need to set parameter on header. You can directly pass that method to 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 is some documentation.



来源:https://stackoverflow.com/questions/61606346/react-navigation-v5-pass-function-as-parameter-to-be-used-in-headerright-butto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!