React Navigation - 右键功能

React Navigation - Right button function

我有一个导航:

const MessageStack = createStackNavigator();
const MessageNavigator = () => (
<MessageStack.Navigator>
    <MessageStack.Screen name="Messages" component={MessagesScreen} />
    <MessageStack.Screen 
        name="Chat" 
        component={ChatScreen} 
        options={({ route }) => ({
            title: route.params.thread.username,
            headerRight: () => (
                <Text style={{paddingEnd:10}} onPress={}>View Profile</Text>
            ),
        })} 
    />
</MessageStack.Navigator>

)

我的聊天屏幕:

function ChatScreen({ route }) {

const { thread } = route.params
const [messages, setMessages] = useState([]);

const createTwoButtonAlert = () =>
Alert.alert(
  "Alert Title",
  "My Alert Msg",
  [
    {
      text: "Cancel",
      onPress: () => console.log("Cancel Pressed"),
      style: "cancel"
    },
    { text: "OK", onPress: () => console.log("OK Pressed") }
  ]
);

来自导航栏中的右侧按钮:

headerRight: () => (
    <Text style={{paddingEnd:10}} onPress={}>View Profile</Text>
),

我想在我的聊天屏幕中调用该功能 createTwoButtonAlert 并显示提醒。

react-native-navigation 网站上有一个示例。

在此示例中,您在 Screen 组件而不是路由器组件中定义 headerRight 属性。

function ChatScreen ({ route, navigation }) {

  const { thread } = route.params
  const [messages, setMessages] = useState([]);

  useLayoutEffect(() => {
    const createTwoButtonAlert = () => {
      Alert.alert(
        'Alert Title',
        'My Alert Msg',
        [
          {
            text: 'Cancel',
            onPress: () => console.log('Cancel Pressed'),
            style: 'cancel'
          },
          { text: 'OK', onPress: () => console.log('OK Pressed') }
        ]
      );
    };

    navigation.setOptions({
      headerRight: () => (
        <Text onPress={() => createTwoButtonAlert()}>View Profile</Text>
      ),
    });
  }, [navigation]);
}

您可以借助 navigation.setOptions()

在您的 ChatScreen 中指定 headerRight 属性
function ChatScreen ({ route, navigation }) {
 
 React.useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <Text style={{ paddingEnd: 10 }} onPress={createTwoButtonAlert}>
          View Profile
        </Text>
      ),
    });
  }, [navigation]);

  const createTwoButtonAlert = () =>
    Alert.alert('Alert Title', 'My Alert Msg', [
      {
        text: 'Cancel',
        onPress: () => console.log('Cancel Pressed'),
        style: 'cancel',
      },
      { text: 'OK', onPress: () => console.log('OK Pressed') },
    ]);

  return (
    //your view
  );
};

勾选这个Live snack