ошибка при назначении функции на навигацию - PullRequest
0 голосов
/ 15 апреля 2019
import React, {Component} from 'react';
import {Platform,StyleSheet,Text,View,TouchableOpacity,Alert,Image,Button} from 'react-native';
import { Dialog } from 'react-native-simple-dialogs';
import AsyncStorage from '@react-native-community/async-storage';

import MapView from 'react-native-maps';
import datum from './data';
import { Marker } from 'react-native-maps';
import Parse from "parse/react-native";


import Geolocation from 'react-native-geolocation-service';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
const homePlace = { description: 'Home', geometry: { location: { lat: 48.8152937, lng: 2.4597668 } }};
const workPlace = { description: 'Work', geometry: { location: { lat: 48.8496818, lng: 2.2940881 } }};


export default class Home extends React.Component{

 static navigationOptions = {
    title: 'Home',
   headerLeft: (
     <Button
       onPress={() => console.log('clicked',"sdsd")}
       title=""
     />
   ),
   headerRight: (
     <Button
       onPress={() => this.toogleauto()}
         color={datum.primaryColor}
       title="Toggle"
     />
   ),
   headerStyle: {
   backgroundColor:datum.secondaryColor,
 },
 headerTintColor:datum.primaryColor,
 headerTitleStyle: {
     fontWeight: '200',
   },
 };



  constructor(props) {
  super(props);

     this.state = {
       lat:13.0474878,
       long:80.0689267,
       picklat:0,
       picklong:0,
       droplat:0,
       droplong:0,
       curautostate:'pick',
       curautostateplaceholder:'Enter your pick up location',
       distance:0

     }
   }

    toogleauto=()=>{
if(this.state.curautostate=='pick'){
 this.setState({curautostate:'drop'})
 this.setState({curautostateplaceholder:'Enter your drop location'})
}else if(this.state.curautostate=='drop'){
   this.setState({curautostate:'pick'})
   this.setState({curautostateplaceholder:'Enter your pick location'})
}else {

}

}

  render() {
    return (

      <View style={{flex:1,flexDirection:'column',backgroundColor:datum.secondaryColor}}>

       <GooglePlacesAutocomplete

       placeholder={this.state.curautostateplaceholder}
       minLength={2} // minimum length of text to search
       autoFocus={false}
       returnKeyType={'search'} // Can be left out for default return key https://facebook.github.io/react-native/docs/textinput.html#returnkeytype
       keyboardAppearance={'light'} // Can be left out for default keyboardAppearance https://facebook.github.io/react-native/docs/textinput.html#keyboardappearance
       listViewDisplayed='false'   // true/false/undefined
       fetchDetails={true}
       renderDescription={row => row.description} // custom description render
       onPress={(data, details = null) => {

         if(this.state.curautostate=='pick'){
          this.setState({picklat:details.geometry.location.lat,picklong:details.geometry.location.lng})

       }else if (this.state.curautostate=='drop'){
         this.setState({droplat:details.geometry.location.lat,droplong:details.geometry.location.lng})
       }
       else {

       }


     }}

       getDefaultValue={() => ''}

       query={{
         // available options: https://developers.google.com/places/web-service/autocomplete
         key: 'AIzaSyCGuEI4rs_vL9HW0xtOeQNy6hngR8dBvhU',
         language: 'en', // language of the results
       // default: 'geocode'
       }}

       styles={{
         backgroundColor:datum.primaryColor,
         textInputContainer: {
           width: '100%'
         },
         textInputContainer: {
        backgroundColor: datum.secondaryColor,
        borderTopWidth: 0,
        borderBottomWidth:0
      },

      textInput: {
        marginLeft: 0,
        marginRight: 0,
        height: 38,
        color: datum.primaryColor,
        fontSize: 16
      },
      predefinedPlacesDescription: {
        color: '#1faadb'
      },
       }}

       nearbyPlacesAPI='GooglePlacesSearch' // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
       GoogleReverseGeocodingQuery={{
         // available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro
       }}
       GooglePlacesSearchQuery={{
         // available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
         rankby: 'distance',

       }}

       GooglePlacesDetailsQuery={{
         // available options for GooglePlacesDetails API : https://developers.google.com/places/web-service/details
         fields: 'formatted_address',
       }}

       filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']} // filter the reverse geocoding results by types - ['locality', 'administrative_area_level_3'] if you want to display only cities


       debounce={200} // debounce the requests in ms. Set to 0 to remove debounce. By default 0ms.



     />

</View>

    );
  }



}

Ожидаемое поведение:

функция будет назначена на нажатие

Что произошло на самом деле

Ошибка Переключение авто не работает

Я только что обрезал много кода для случаев переполнения стека, на самом деле, у меня очень четкий вопрос, что мешает, пока toggleauto функция назначена на пресс-реквизит, потому что приложение вылетает при нажатии этой кнопки навигации, но консоль .log работает нормально, но мне нужно запустить собственную функцию

1 Ответ

0 голосов
/ 15 апреля 2019

создайте свою функцию поверх вашего кода:

   toogleauto=()=>{
if(this.state.curautostate=='pick'){
 this.setState({curautostate:'drop'})
 this.setState({curautostateplaceholder:'Enter your drop location'})
}else if(this.state.curautostate=='drop'){
   this.setState({curautostate:'pick'})
   this.setState({curautostateplaceholder:'Enter your pick location'})
}else {

}

}


        .
         .
         .
         and other codes 
 static navigationOptions = {
    title: 'Home',
   headerLeft: (
     <Button
       onPress={() => console.log('clicked',"sdsd")}
       title=""
     />
   ),
   headerRight: (
     <Button
       onPress={() => this.toogleauto()}
         color={datum.primaryColor}
       title="Toggle"
     />
   ),
   headerStyle: {
   backgroundColor:datum.secondaryColor,
 },
 headerTintColor:datum.primaryColor,
 headerTitleStyle: {
     fontWeight: '200',
   },
 };

или связать его напрямую:

 headerRight: (
     <Button
       onPress={() => {
          //your function code 
          }}
         color={datum.primaryColor}
       title="Toggle"
     />
   ),
...