我是React Native的新手。

我要做的是制作类似Google Maps的应用程序。在MainMap.js屏幕上,当我们进入时,屏幕将立即生成2个搜索栏。第一个将带有文本"Your location"。第二个以此类推,以此类推,将为空,以便用户键入搜索位置。

但是,我在FlatList组件方面遇到了一些问题。在我的PlaceInput组件中,我将defaultValue作为道具用于文本输入。然后在MainMap.js中,我将拥有一个最初设置为"Your Location"的状态,然后当null从第二个FlatList组件开始渲染时,将其更改为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以引入另一个道具以指示是否显示默认值。

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/

10-11 13:34