首页 > 解决方案 > How do I add custom title and button to a header in React Native?

问题描述

I have a simple page with list of students. Once I click on each student profile, I want to go to a new page, where the title of the page will be the name of the student and where I will have a button on the right. All of this should be done in the header. So I put the following code:

<Stack.Screen name="Profile" component={ProfileScreen}
                  options={({ route }) => ({ title: route.params.name })}
 /> 

Which correctly displays the name of the student on the header. Then I wanted to add the button on the right and as written here I changed my code to:

<Stack.Screen name="Profile" component={ProfileScreen}
                  options={{ headerTitle: ({route}) => ({ title: route.params.name }),
                             headerRight: () => (
                                                <Button
                                                    onPress={() => alert('This is a button!')}
                                                    title="Info"
                                                    color="#fff"
                                                  />),
                          }}
              />

And now I have the following error: TypeError: undefined is not an object (evaluating 'route.params') Can someone advice how to add both custom title and button

标签: react-native

解决方案


You will have to pass it like below

   options={({ route }) => ({
      title: route.params.name,
      headerRight: () => (
        <Button
          onPress={() => alert('This is a button!')}
          title="Info"
          color="#fff"
        />
      ),
    })}

推荐阅读