在搜索栏中输入文本不会过滤掉名称

时间:2019-08-12 14:18:39

标签: react-native ecmascript-6 searchbar

我是RN的新手,我刚刚使用react-native-elements在目录页面中创建了搜索栏。但是,当我在搜索栏中键入字符名称时,不会触发任何操作。我认为自己的状态设置正确,因为我遵循了文档。任何人都可以看一下这个问题,并弄清可能出什么问题了吗?

这就是我设置搜索栏文件夹的方式。

//SearchHeader.js
import React from "react";
import {
  Button,
  View,
  Text,
  StyleSheet,
  Platform,
  Animated,
  ScrollView,
  ImageBackground,
  TouchableOpacity
} from "react-native";
import {
  createStackNavigator,
  createAppContainer,
  createBottomTabNavigator
} from "react-navigation";
import { SearchBar } from "react-native-elements";
// import MaterialCommunications from 'react-native-vector-icons';
export default class SearchHeader extends React.Component {
  state = {
    search: ""
  };
  updateSearch = search => {
    this.setState({ search });
  };
  render() {
    const { search } = this.state;
    return (
      <View style={styles.container}>
        <SearchBar
          inputStyle={{ backgroundColor: "white" }}
          placeholder="Search for a character..."
          placeholderTextColor={"#g5g5g5"}
          onChangeText={this.updateSearch}
          value={search}
        />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    height: 50,
    width: 390,
    justifyContent: "center",
    marginTop: 50
  }
});

这是我将其导入目录文件夹的方式:

//EmployeeDirectory.js

import React from "react";
import {
  Button,
  View,
  Text,
  StyleSheet,
  Platform,
  Animated,
  ScrollView,
  ImageBackground,
  TouchableOpacity
} from "react-native";
import SearchHeader from './SearchHeader';
import { withNavigation } from "react-navigation";
import {
  createStackNavigator,
  createAppContainer,
  createBottomTabNavigator
} from "react-navigation";
import { SearchBar } from "react-native-elements";


class EmployeeDirectory extends React.Component {
  static navigationOptions = ({ navigation }) => ({
    title: "Character Directory",
    headerStyle: {
      backgroundColor: "#53b4e6"
    },
    headerTintColor: "#f6c945",
    headerTitleStyle: {
      fontWeight: "bold"
    }
  });

  render() {
    return (
      <View style={styles.container}>
         <ImageBackground
          source={{
            uri:
              "https://backgrounddownload.com/wp-content/uploads/2018/09/simpsons-clouds-background-5.jpg"
          }}
          style={{
            width: "100%",
            height: "100%",
            alignContent: "center",
            justifyContent: "center",
            alignItems: "center"
          }}
        >

          <SearchHeader />

          <TouchableOpacity
            onPress={() => this.props.navigation.navigate("HomerSimpson")}
            style={styles.button}
          >
            <Text style={styles.text}>Homer Simpson</Text>
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => this.props.navigation.navigate("BartSimpson")}
            style={styles.button}
          >
            <Text style={styles.text}>Bart Simpson</Text>
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => this.props.navigation.navigate("MargeSimpson")}
            style={styles.button}
          >
            <Text style={styles.text}>Marge Simpson</Text>
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => this.props.navigation.navigate("LisaSimpson")}
            style={styles.button}
          >
            <Text style={styles.text}>Lisa Simpson</Text>
          </TouchableOpacity>  
        </ImageBackground>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
    alignContent: "center"
  },
  text: {
    fontSize: 25,
    fontWeight: "bold",
    color: "#f6c945",
    alignItems: "center",
    justifyContent: "center",
    alignContent: "center"
  },
  button: {
    flexDirection: "row",
    backgroundColor: "#2d98da",
    alignItems: "center",
    justifyContent: "center",
    alignContent: "center",
    marginTop: 10,
    marginBottom: 10,
    borderRadius: 10,
    borderWidth: 1.0,
    borderColor: "black",
    height: 30,
    width: 260
  }
});
export default withNavigation(EmployeeDirectory)

1 个答案:

答案 0 :(得分:1)

我给你举个例子。

import * as React from 'react';
import { Text, View, StyleSheet, FlatList, ActivityIndicator, Platform } from 'react-native';
import { SearchBar } from 'react-native-elements';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    //setting default state
    this.state = { isLoading: true, search: '' };
    this.arrayholder = [];
  }
  componentDidMount() {
    return fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response => response.json())
      .then(responseJson => {
        this.setState(
          {
            isLoading: false,
            dataSource: responseJson,
          },
          function() {
            this.arrayholder = responseJson;
          }
        );
      })
      .catch(error => {
        console.error(error);
      });
  }
  search = text => {
    console.log(text);
  };
  clear = () => {
    this.search.clear();
  };
  SearchFilterFunction(text) {
    //passing the inserted text in textinput
    const newData = this.arrayholder.filter(function(item) {
      //applying filter for the inserted text in search bar
      const itemData = item.title ? item.title.toUpperCase() : ''.toUpperCase();
      const textData = text.toUpperCase();
      return itemData.indexOf(textData) > -1;
    });
    this.setState({
      //setting the filtered newData on datasource
      //After setting the data it will automatically re-render the view
      dataSource: newData,
      search:text,
    });
  }
  ListViewItemSeparator = () => {
    //Item sparator view
    return (
      <View
        style={{
          height: 0.3,
          width: '90%',
          backgroundColor: '#080808',
        }}
      />
    );
  };
  render() {
    if (this.state.isLoading) {
      //Loading View while data is loading
      return (
        <View style={{ flex: 1, paddingTop: 20 }}>
          <ActivityIndicator />
        </View>
      );
    }
    return (
      //ListView to show with textinput used as search bar
      <View style={styles.viewStyle}>
        <SearchBar
          round
          searchIcon={{ size: 24 }}
          onChangeText={text => this.SearchFilterFunction(text)}
          onClear={text => this.SearchFilterFunction('')}
          placeholder="Type Here..."
          value={this.state.search}
          />
          <FlatList
          data={this.state.dataSource}
          ItemSeparatorComponent={this.ListViewItemSeparator}
          //Item Separator View
          renderItem={({ item }) => (
            // Single Comes here which will be repeatative for the FlatListItems
            <Text style={styles.textStyle}>{item.title}</Text>
          )}
          enableEmptySections={true}
          style={{ marginTop: 10 }}
          keyExtractor={(item, index) => index.toString()}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  viewStyle: {
    justifyContent: 'center',
    flex: 1,
    backgroundColor:'white',
    marginTop: Platform.OS == 'ios'? 30 : 0
  },
  textStyle: {
    padding: 10,
  },
});

Sites referenced在示例中