javascript 为什么我的组件在web视图上垂直居中,而不是在react native / expo应用程序的原生视图上

jxct1oxe  于 2023-05-05  发布在  Java
关注(0)|答案(1)|浏览(165)

我正在尝试使用flex将我的搜索组件(水平和垂直)居中。它在web视图上工作正常,但在本机视图上不能垂直居中。我正在使用Expo,它有几种可用的方法来查看应用程序:

这里是App.tsx

import React from 'react';
import { View } from 'react-native';
import Search from './components/Search';

const styles: any = {
  container:{
    flex: 1,
    margin: 20,
    alignItems: 'center',
    justifyContent: 'center'
  }
}
const App = () => {

  return (
    <View style={styles.container} >
      <Search/>
    </View>
  );
};

export default App;

这里是Search.tsx

import React, { useState, useEffect } from 'react';
import { View, TextInput, FlatList, Text } from 'react-native';

const Search = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [results, setResults] = useState([]);

  useEffect(() => {
    let timerId: any = null;
    if (searchTerm.length >= 2) {
      clearTimeout(timerId);
      timerId = setTimeout(() => {
        fetch(`http://localhost:8080/search/${searchTerm}`)
          .then((response) => response.json())
          .then((data) => setResults(data.results))
          .catch((error) => console.error(error));
      }, 500);
    } else {
      setResults([]);
    }

    return () => clearTimeout(timerId);
  }, [searchTerm]);

  return (
    <View>
      <TextInput
        value={searchTerm}
        onChangeText={(text) => setSearchTerm(text)}
        placeholder="Search"
      />
      <FlatList
        data={results}
        keyExtractor={(item) => item}
        renderItem={({ item }) => (
          <Text>{item}</Text>
        )}
      />
    </View>
  );
};

export default Search;
zlwx9yxi

zlwx9yxi1#

搜索中的视图将覆盖整个屏幕,其中的列表将只占用所需的空间。应用Flex:1到您的flatlist或justifyItems:“中心”到 Package 视图。

相关问题