javascript - 如何更改 FlatList 中 TextInput 组件的属性?

标签 javascript reactjs react-native

我是 React Native 的新手。

我想做的是制作一个类似谷歌地图的应用程序。在MainMap.js屏幕上,当我们输入时,屏幕会立即生成2个搜索栏。第一个将包含文本“您的位置”。第二个等等将为空,供用户输入搜索位置。

但是,我在使用 FlatList 组件时遇到了一些问题。在我的 PlaceInput 组件中,我使用 defaultValue 作为文本输入的 prop。然后在 MainMap.js 中,我将有一个状态,最初设置为 “您的位置”,然后我将其更改为 nullFlatList 开始从第二个 PlaceInput 组件渲染时。

这是MainMap.js*

import React from 'react';
import { 
    TouchableWithoutFeedback,
    StyleSheet,
    Keyboard,
    PermissionsAndroid,
    Platform, 
    View,
    Button,
    FlatList,
    Dimensions
} from 'react-native';

import PlaceInput from '../components/PlaceInput';

import axios from 'axios';
import PolyLine from '@mapbox/polyline';
import MapView, {Polyline, Marker} from 'react-native-maps';
import Geolocation from 'react-native-geolocation-service';

const INCREMENT = 1;
const HEIGHT = Dimensions.get('window').height;
const WIDTH = Dimensions.get('window').width;

class MainMap extends React.Component{

    constructor(props){
        super(props);

        this.state={

            _userLocationDisplayed: null,
            userLatitude: 0,
            userLongitude: 0,

            numOfInput:[0,1],
            counter: 1,
        };
    };
    componentDidMount(){
        this._requestUserLocation();
    };

    // Get user current location

    // Ask user permission for current location
    // Request the Directions API from Google
    // Get the formatted_address & name from Google Places API
    // Adding a search bar
    onAddSearch(){
        this.setState((state) => ({
            counter: state.counter + INCREMENT,
            numOfInput: [...state.numOfInput, state.counter],
        }));
    };

    onChangeSearchDisplay(){
        this.setState({
            _userLocationDisplayed: null
        })
    };

    render(){

            return(
                <TouchableWithoutFeedback onPress={this.hideKeyboard} >
                    <View style={styles.container} >
                        <View style={{height: HEIGHT/2.5 }}>
                            <FlatList
                                data={this.state.numOfInput}
                                keyExtractor={(item, index) => item}
                                renderItem={itemData => {
                                    return(
                                        <PlaceInput
                                            id={itemData.item}
                                            onDelete={this.onDeleteSearch}
                                            showDirectionOnMap={this.showDirectionOnMap}
                                            userLatitude={userLatitude}
                                            userLongitude={userLongitude}
                                            userLocationDisplayed={this.state._userLocationDisplayed}
                                        />
                                    )
                                }}
                            />
                        </View>
                    </View>
                </TouchableWithoutFeedback>
            )
        }

    }

//}


export default MainMap;

const styles = StyleSheet.create({
    container:{
        flex: 1
    },
    map:{
        ...StyleSheet.absoluteFillObject
    },
});


这是 PlaceInput 组件

import React from 'react';
import {
    View,
    TextInput,
    StyleSheet,
    Text,
    Dimensions,
    TouchableOpacity,
    Keyboard,
} from 'react-native';
import axios from 'axios';
import _ from 'lodash'
import Icon from 'react-native-vector-icons/MaterialCommunityIcons'

const WIDTH = Dimensions.get('window').width;
const HEIGHT = Dimensions.get('window').height;

class PlaceInput extends React.Component{

    constructor(props){
        super(props);
        this.state={
            ...
        }
        ...
    }

    render() {
        // console.log(this.state);
        // Code for displaying the suggestions from the Google Place API
        // Don't care about it too much :)))
        const predictions = this.state.predictions.map(prediction => {
            const { id, structured_formatting, place_id } = prediction;
            return(
                <TouchableOpacity 
                    key={id} 
                    onPress={() => this.setDestination(structured_formatting.main_text, place_id)}    
                >
                    <View style={styles.suggestion}>
                        <Text style={styles.mainText}>{structured_formatting.main_text}</Text>
                        <Text style={styles.secText}>{structured_formatting.secondary_text}</Text>
                    </View>
                </TouchableOpacity>
            );
        } )

        return (
            <View style={{flex: 1, flexDirection: 'column'}} key={this.props.id}>
                <View style={styles.buttonContainer}>
                    <View style={{flex: 1, alignItems: 'center'}}>
                            <Text style={{fontSize: 8}}>{'\u25A0'}</Text>
                    </View>
                    <View style={{flex: 4}}>
                        <TextInput 
                            key={this.id}
                            autoCorrect={false}
                            autoCapitalize='none'
                            style={styles.inputStyle}
                            placeholder='Search your places'
                            onChangeText={(input) => {
                                this.setState({destinationInput: input});
                                this.getPlacesDebounced(input);
                            }}
                            value={this.state.destinationInput}

                            {/*What I'm trying here as mentioned*/}
                            defaultValue={this.props.userLocationDisplayed}

                        />
                    </View>
                    <View style={styles.rightCol}>
                            <TouchableOpacity onPress={() => this.props.onDelete(this.props.id)}>
                                <Icon name='delete' size={25} style={{alignSelf: 'center'}} />
                            </TouchableOpacity>
                    </View>

                </View>
                {predictions}
            </View>
        )
    } 
}

const styles = StyleSheet.create({
    buttonContainer:{
        flexDirection: 'row',
        height: (HEIGHT - 690),
        width: (WIDTH-48),
        marginTop: 55,
        padding: 5,
        backgroundColor: 'white',
        shadowColor: '#000000',
        elevation: 7,
        shadowRadius: 5,
        shadowOpacity: 1,
        borderRadius: 5,
        alignItems: 'center',
        alignSelf:'center'
    },
    inputStyle:{
        fontFamily: 'sans-serif-thin', 
        fontSize: 16, 
        color: 'black',
        fontWeight: 'bold'
    },
    suggestion:{
        backgroundColor: 'white',
        padding: 10,
        borderWidth: 0.5,
        width: (WIDTH-48),
        alignSelf: 'center'
    },
    secText:{
        color: '#777'
    },
    mainText:{
        color: '#000'
    },
    rightCol:{
        flex: 1,
        borderLeftWidth: 1,
        borderColor: '#ededed',
    },
})

export default PlaceInput;

我很想听听您对我的帮助的评论。

另外,请随意给出其他方法,因为我认为我的方法还不够优化。我也在为生产构建这个。

最佳答案

如果我正确理解你的问题,你是在问如何根据 prop 值在平面列表数据中的位置有条件地设置它。基本上,您希望第一个 PlaceInput 组件显示“输入的”文本值“您的位置”,而其余组件则没有任何内容。

更新 PlaceInput 的 API 以接受另一个 prop 来指示是否显示默认值。

PlaceInput.js

...
<TextInput 
  key={this.id}
  autoCorrect={false}
  autoCapitalize='none'
  style={styles.inputStyle}
  placeholder='Search your places'
  onChangeText={(input) => {
    this.setState({destinationInput: input});
    this.getPlacesDebounced(input);
  }}
  value={this.state.destinationInput}
  defaultValue={this.props.displayDefaultValue ? this.props.defaultValue : null}
/>
...

并传入任何特定的 PlaceInput 是否应显示它。由于您希望显示第一个,而其余部分不显示,因此使用数组索引是一个不错的起点。在这里,我们可以利用这样一个事实:在javascript中,0是一个假值,而所有其他数字都是真值。使用 !index!0true!1, !2,等等,都是false

MainMap.js

<FlatList
  data={this.state.numOfInput}
  keyExtractor={(item, index) => item}
  renderItem={({ index, item }) => {
    return(
      <PlaceInput
        id={item}
        defaultValue="Your Location"
        displayDefaultValue={!index} // index 0 is falsey, all others truthy
        onDelete={this.onDeleteSearch}
        showDirectionOnMap={this.showDirectionOnMap}
        userLatitude={userLatitude}
        userLongitude={userLongitude}
        userLocationDisplayed={this.state._userLocationDisplayed}
      />
    )
  }}
/>

关于javascript - 如何更改 FlatList 中 TextInput 组件的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60708221/

相关文章:

reactjs - Firebase Firestore onSnapshot PayloadTooLargeError : request entity too large on Expo/React Native project

javascript - react native Android WebView : javaScriptEnabled does not seem to be working

javascript - HTML 字段类型 仅输入数字或仅输入字母,无需 JavaScript

javascript - 用 async/await 重写 promises,寻求澄清

javascript - 如何将自定义 polymer 元素的属性绑定(bind)到 angularjs

javascript - 在 Android 上使用地理定位或 MapView react Native expo 项目错误

react-native - react 原生 fs 库不写入文件

javascript - HTML Select 在搜索中出现问题

javascript - 将项目数据从 JSON 文件动态加载到 React 中

javascript - 未捕获的类型错误 : Cannot read property 'filterText' of undefined