Home > Net >  How to give two different function to the same button when it's located on different screen?
How to give two different function to the same button when it's located on different screen?

Time:02-20

page 1

My FlatList looks like below.

    <FlatList
      ref={flatListRef}
      contentContainerStyle={{
        paddingBottom: 20,
      }}
      keyboardDismissMode={true}
      showsVerticalScrollIndicator={false}
      data={state}
      keyExtractor={(comment) => ""   comment.id}
      renderItem={renderComment}
    />

and rendercomment looks like below. As you can see, it goes to CommentRow screen with data.

  const renderComment = ({ item: commentsRow }) => {
    const { comments } = getValues();
    return (
      <CommentRow
        commentsRow={commentsRow}
        photoId={route?.params?.photoId}
        updatedComments={comments}
        textRef={textRef}
      />
    );
  };

And when I press confirm button, it can create the comment.

    <ConfirmButton onPress={handleSubmit(onValid)}>
      <ConfirmText>확인</ConfirmText>

page 2

If we go to CommentRow screen. if I press Edit button, i want to edit my comment.

      <TouchableOpacity onPress={onEditClick}>
        <WriteComment>수정</WriteComment>

But Problem is when I press edit button, I need to change the payload of comment with the same button which is confirm button of Comment. So when i press confirm button, it doesn't edit comment but it create comment.

If this components are in one page, then I can use useState in order to distinguish edit button from confirm button. But since they are in two screen separately, I can't send the info that this is edit button from page 2 to page 1. because flatlist only pass data from page 1 to page 2.

I've struggled with this issue for 1 week :( have you any idea for this?

CodePudding user response:

You could pass a callback function from page 1 to page 2 as follows.

 const onUpdateComment = React.useCallback((newComment) => {
    // update state here for setting the new comment
 }, [whatever you need here])

 const renderComment = ({ item: commentsRow }) => {
    const { comments } = getValues();
    return (
      <CommentRow
        commentsRow={commentsRow}
        photoId={route?.params?.photoId}
        comments={comments}
        updateComments={onUpdateComment} // this has changed on page 1
        textRef={textRef}
      />
    );
  };

On page 2 you can use the passed callback function.

const onEditClick = React.useCallback(() => {
  // do the other stuff
  updateComments(newComment) // this is the callback function passed in the updateComments prop of CommentRow in page 1
}, [whatever you need here])
<TouchableOpacity onPress={onEditClick}>
  • Related