web-dev-qa-db-fra.com

React Liste déroulante de recherche native

Je travaille sur React application native. Je recherche une liste déroulante consultable que je dois implémenter à de nombreux endroits.

Ci-dessous, voir la vidéo ci-dessous pour référence:

exemple de vidéo

J'ai implémenté des tiers ci-dessous mais ils ne sont pas les mêmes que ceux dont j'ai besoin:

  1. https://www.npmjs.com/package/react-native-searchable-dropdown

  2. https://www.npmjs.com/package/react-native-searchable-selectbox

  3. https://github.com/toystars/react-native-multiple-select

5
Anjana

J'ai essayé d'implémenter quelque chose de similaire il y a quelque temps et à l'époque, j'ai abandonné l'idée d'avoir une liste déroulante car elle était incohérente sur les deux plates-formes et je ne pouvais pas trouver une solution parfaite. Je ne peux pas voir votre vidéo mais je pense que je sais où vous allez avec ça. Voici mon conseil: je créerais un écran séparé qui s'ouvre sur le robinet de ce composant qui serait une "liste déroulante", et y créerais une liste consultable/filtrable. Vous pouvez essayer de le faire en utilisant ceci: https://www.npmjs.com/package/searchable-flatlist , ou créez votre propre flatlist, qui est super facile et permet plus de personnalisation! EDIT: Si vous ne voulez pas d'écran séparé, utilisez ceci: https://www.npmjs.com/package/react-native-searchable-dropdown

1
Annie Hill

essayez d'en implémenter un:

const sports = ["Badminton","Cricket","Chess","Kho-Kho","Kabbadi","Hockey","Boxing","Football","Basketball","Volleyball","Tennis","Table Tennis"];

predict(){
    let q = this.state.query;
    let arr = sports.filter(ele => ele.toLowerCase().indexOf(q.toLowerCase()) != -1).splice(0,5);
    this.setState((prev = this.state)=>{
        let obj={};
        Object.assign(obj,prev);
        obj.predictions.splice(0,obj.predictions.length);
        arr.forEach(ele=>{
            obj.predictions.Push({key : ele});
        });
        return obj;
    });
}

<TouchableWithoutFeedback onPress={()=>{this.setState({done : true})}}>
                <ScrollView
                    keyboardShouldPersistTaps='handled'
                    contentContainerStyle={style.content}
                >
                    <View>
                        <TextInput 
                            onChangeText={(text)=>{
                                this.setState({query : text , done : false});
                                this.predict();
                            }}  
                            placeholder="What do you want to play ?" 
                            placeholderTextColor="#A6A4A4"
                            value = {this.state.query}
                            onSubmitEditing = {()=>{this.setState({done : true})}}
                            underlineColorAndroid = "#0098fd"
                        ></TextInput>
                        <TouchableOpacity onPress={()=>{this.filteredEvents()}}><Icon name="search" color = "#0098fd" size = {20}></Icon></TouchableOpacity>
                    </View>


                    {
                        this.state.predictions.length != 0 && !this.state.done &&
                        <FlatList 
                            style={styles.predictor_view}
                            data={this.state.predictions}
                            extraData = {this.state}
                            renderItem = {
                                ({item})=>(
                                        <TouchableOpacity 
                                        style={styles.predictions} 
                                        onPress={()=>{
                                            console.log('ok');
                                            this.setState({query : item.key,done : true});
                                            console.log(this.state);
                                        }}>
                                            <Text>{item.key}</Text>
                                        </TouchableOpacity>
                                )
                            }
                        />
                    }
                </ScrollView>
            </TouchableWithoutFeedback>
1
Nitin Garg

J'ai utilisé react-native-autocomplete-input

J'ai écrit un composant pour aider dans la liste déroulante: customDropDownComponent.js

/*This is an example of AutoComplete Input/ AutoSuggestion Input*/
import React, { Component } from 'react';
import { StyleSheet, Text, TouchableOpacity, View, Button, ScrollView } from 'react-native';
//import all the components we are going to use.
import Autocomplete from 'react-native-autocomplete-input'
//import Autocomplete component


class CustomDropDownComponent extends Component {
    constructor(props) {
        super(props);
        //Initialization of state
        //films will contain the array of suggestion
        //query will have the input from the autocomplete input
        this.state = {
            query: '',
            data: [],
            dataDuplicate:[],
            itemSelected: false
        };
    }
    componentDidMount() {
      //Loading all data
        this.loadData()


    }
    
    findElement(query, text, itemSelected) {
        //method called everytime when we change the value of the inputquery === '' || 
        if (itemSelected === true||query==='') {
            //if the query is null or an item is selected then return blank
            return [];
        }
        //making a case insensitive regular expression to get similar value from the data json
        const regex = new RegExp(`${query.trim()}`, 'i');
        //return the filtered data array according the query from the input
        var newList = [];
        var result = this.state.IATADup.filter(data => {
            if (data.id.search(regex) === 0) {
                newList.Push(data);
                return false;
            } else {
                return data.id.search(regex) >= 0;
            }
        });
        result = newList.concat(result);
        this.props.adjustMargin(1, result.length);//expadnding space in page to make room for dropdown
        this.setState({ data: result, query: text, itemSelected: itemSelected });
    }

    loadData = () => {
        var dataToLoad = Commondata.aircraftDetail
        dataToLoad.sort(function (a, b) {
            if (a.id > b.id) {
                return 1;
            }
            if (b.id > a.id) {
                return -1;
            }
            return 0;
        });
        this.setState({
            dataDuplicate: dataToLoad
        })
    }

    render() {
        const { query } = this.state;
        const data = this.state.data;
        const comp = (a, b) => a.toLowerCase().trim() === b.toLowerCase().trim();
        var inputContainerStyle = styles.inputContainerStyle;
        if (this.props.destinationBorder === "#FF0000") {
            inputContainerStyle = styles.inputContainerRedStyle;
        }

        return (

            <View style={styles.container}  >
                <Autocomplete
                    autoCapitalize="none"
                    autoCorrect={false}
                    flatListProps={{ nestedScrollEnabled: true }}
                    containerStyle={styles.autocompleteContainer}
                    listStyle={styles.listStyle}
                    inputContainerStyle={inputContainerStyle}
                    data={data}
                    keyExtractor={(item, i) => { return i } 
                    defaultValue={query}
                    onChangeText={text => {
                        //handle input
                        if (text.trim() === "") this.props.adjustMarginBack();//adjust margin to normal in case of empty searrch element
                        this.findElement(text, text, false);//search for element
                    }}
                    placeholder={en.pick_one}
                    renderItem={({ item }) => (
                        //you can change the view you want to show in suggestion from here
                        <TouchableOpacity onPress={() => {
                            this.props.adjustMarginBack()
                            this.setState({ query: item.id, itemSelected: true, data: [] });
                        }}>
                            <Text style={styles.itemText}>
                                {item.id}
                            </Text>
                            <Text style={styles.itemSubText}>
                                {item.name}
                            </Text>
                        </TouchableOpacity>
                    )}
                />


            </View>

        );
    }
}
const styles = StyleSheet.create({
    container: {
        backgroundColor: '#F5FCFF'
    },
    autocompleteContainer: {
        backgroundColor: '#ffffff',
        borderWidth: 0,

    },
    inputContainerStyle: {
        borderWidth: 0.5, borderColor: '#D9D9D9', padding: '1.5%'
    },
    inputContainerRedStyle: {
        borderWidth: 0.5, borderColor: '#FF0000', padding: '1.5%'
    },
    descriptionContainer: {
        flex: 1,
        justifyContent: 'center',
        padding: '5%'
    },
    itemText: {
        fontSize: 15,
        paddingTop: 5,
        paddingBottom: 5,
        margin: 2,
    },
    itemSubText: {
        fontSize: 10,
        paddingTop: 5,
        paddingBottom: 5,
        margin: 2,
        marginLeft: 10
    },
    infoText: {
        textAlign: 'center',
        fontSize: 16,
    },
    listStyle: {
        height: 100,
        position: "relative",
        zIndex: 999
    }
});
export default CustomComponent;

Maintenant sur l'écran d'affichage:

app.js

import React, { Component } from 'react';
import { View, Text, ScrollView } from 'react-native';
import CustomDropDownComponent from './CustomDropDownComponent.js'

export default class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }

    render() {
        return (
            <View>
                <ScrollView
                    nestedScrollEnabled={true}
                    keyboardShouldPersistTaps={'handled'}>
                    <CustomDropDownComponent /*Handle all inputs and margin resets as props *//>
                </ScrollView>
            </View>
        );
    }
}
0
Naveen kirugulige