0

在我的 React Native (Expo) 应用程序中,我想将React Navigation从 V5 升级到 V6。但是,我无法使TextInput堆栈导航器标题全角。我尝试'auto'了样式'100%'width价值,但是对于真正的宽文本框都没有帮助。

这是用于复制的世博小吃的链接:https ://snack.expo.io/@vahdet/reactnavigation6-headerbar ,其App.js内容如下。我想我在以下方面缺乏一些flexbox知识headerSearchBarStyle

import React, { useLayoutEffect, useState } from 'react';
import { Text, TextInput, View, StyleSheet } from 'react-native';
import { NavigationContainer, useNavigation } from '@react-navigation/native';
import { enableScreens } from 'react-native-screens';
import { AppearanceProvider } from 'react-native-appearance';
import { StatusBar } from 'expo-status-bar';
import { createStackNavigator } from '@react-navigation/stack';

enableScreens();
const HomeStack = createStackNavigator();

const Search = () => {
  const navigation = useNavigation();
  const [searchText, setSearchText] = useState('');

  // Customize header
  useLayoutEffect(() => {
    navigation.setOptions({
      headerTitle: () => (
        <TextInput
          style={styles.headerSearchBarStyle}
          value={searchText}
          onChangeText={(val) => setSearchText(val)}
          containerStyle={styles.searchBarContainerStyle}
          placeholder="Search..."
          returnKeyType="search"
          textContentType="none"
          cancelButtonTitle="Cancel"
        />
      )
    })
  }, [navigation, searchText]);

  return (
    <View style={styles.view}>
      {!searchText ? (
        <Text>Search results go here</Text>
      ) : (
        <Text>Initial (no search) content goes here</Text>
      )}
    </View>
  )
}

const App = () => {
  return (
    <AppearanceProvider>
      <StatusBar style="auto" />
      <NavigationContainer>
        <HomeStack.Navigator initialRouteName="Search">
          <HomeStack.Screen name="Search" component={Search} />
        </HomeStack.Navigator>
        </NavigationContainer>
    </AppearanceProvider>
  );
}

const styles = StyleSheet.create({
  headerSearchBarStyle: {
    width: 'auto', // also tried '100%'
    borderColor: 'black',
    borderWidth: 1,
    backgroundColor: 'transparent'
  },
});

export default App;

编辑:在Kartikey 的方法之后,我想通过full-width详细说明,我不一定指全屏宽度:可能同时存在headerLeft(例如后退按钮)或headerRight组件的场景。

4

1 回答 1

0

使用设备宽度

import { Dimensions } from "react-native";

const ScreenWidth = Dimensions.get('window').width;

headerSearchBarStyle: {
    width: ScreenWidth,
    borderColor: 'black',
    borderWidth: 1,
    backgroundColor: 'transparent',
    margin: 10,
  },

您也可以将其设置为width: ScreenWidth - 30,只是为了留出一些余量

工作示例

于 2021-07-18T20:46:47.127 回答