简体   繁体   English

如何在本机反应中使用ES6

[英]how to use ES6 with react native

Working with React-Native and trying to learn ES6 syntax. 使用React-Native并尝试学习ES6语法。 I had a similar issue yesterday and got the solution. 昨天我遇到了类似的问题,并找到了解决方案。 I added 我加了

.bind(this) .bind(this)

to my my function calls and the problem was solved. 到我的函数调用,问题就解决了。 I ran into the same issue again with another function call and I cannot track down what is going on. 我再次遇到另一个函数调用,遇到同样的问题,无法追踪正在发生的事情。 The error message is the same. 错误消息是相同的。

undefined is not a object (evaluating 'this.props.drawer.open') 未定义不是对象(评估“ this.props.drawer.open”)

The function is: 该函数是:

    onClickMenu () {
    this.props.drawer.open();
  }

and it is being called with this: 它被这样调用:

onPress={this.onClickMenu.bind(this)}

Here is the entire code. 这是完整的代码。 If you see something other than this issue that doesn't look right let me know please! 如果您发现此问题之外的其他问题,请与我联系! *note I have replaced "var" with "let". *请注意,我已将“ var”替换为“ let”。 From what I've read it is proper ES6 syntax to do that everywhere? 从我阅读的内容来看,在任何地方都可以使用正确的ES6语法吗?

    'use strict';

const React = require('react-native');
const {
  Text,
  View,
  Component,
  StyleSheet,
  SwitchAndroid
} = React;

import { Button } from 'react-native-material-design';
import Store from 'react-native-simple-store';
import Underscore from 'underscore';
import RNGMap from 'react-native-gmaps';
import Polyline from 'react-native-gmaps/Polyline';
import Icon from 'react-native-vector-icons/Ionicons';
import SettingsService from './../settings/settings.service';
//import subdivisions from './subdivisions.json';
import commonStyles from './../common/styles';

let accessToken = null;
let userId = null;
let routeId = null;
let subdivisionId = null;

SettingsService.init('Android');

class Map extends Component {
  constructor(props) {
    super(props)
    this.state = {
      odometer: 0,
      mapWidth: 300,
      mapHeight: 300,
      enabled: false,
      isMoving: false,
      currentLocation: undefined,
      locationManager: undefined,
      paceButtonIcon: 'Start Trip',
      navigateButtonIcon: 'navigate',
      paceButtonStyle: commonStyles.disabledButton,
      // mapbox
      center: {
        lat: 40.7223,
        lng: -73.9878
      },
      zoom: 10,
      markers: []
    }
  }

  componentDidMount() {
    Store.get('token').then((token) => {
      accessToken = token.access_token;
      userId = token.userId;
    });
    let me = this,
      gmap = this.refs.gmap;

    this.locationManager = this.props.locationManager;

    // location event
    this.locationManager.on("location", function(location) {
      console.log('- location: ', JSON.stringify(location));
      me.setCenter(location);
      gmap.addMarker(me._createMarker(location));

      me.setState({
        odometer: (location.odometer / 1000).toFixed(1)
      });

      // Add a point to our tracking polyline
      if (me.polyline) {
        me.polyline.addPoint(location.coords.latitude, location.coords.longitude);
      }
    });
    // http event
    this.locationManager.on("http", function(response) {});
    // geofence event
    this.locationManager.on("geofence", function(geofence) {});
    // error event
    this.locationManager.on("error", function(error) {
      console.log('- ERROR: ', JSON.stringify(error));
    });
    // motionchange event
    this.locationManager.on("motionchange", function(event) {
      me.updatePaceButtonStyle();
    });

    // getGeofences
    this.locationManager.getGeofences(function(rs) {
    }, function(error) {
      console.log("- getGeofences ERROR", error);
    });

    SettingsService.getValues(function(values) {
      values.license = "eddbe81bbd86fa030ea466198e778ac78229454c31100295dae4bfc5c4d0f7e2";
      values.orderId = 1;
      values.stopTimeout = 0;
      //values.url = 'http://192.168.11.120:8080/locations';

      me.locationManager.configure(values, function(state) {
        me.setState({
          enabled: state.enabled
        });
        if (state.enabled) {
          me.initializePolyline();
          me.updatePaceButtonStyle()
        }
      });
    });

    this.setState({
      enabled: false,
      isMoving: false
    });
  }
  _createMarker(location) {
    return {
      title: location.timestamp,
      id: location.uuid,
      icon: require("image!transparent_circle"),
      anchor: [0.5, 0.5],
      coordinates: {
        lat: location.coords.latitude,
        lng: location.coords.longitude
      }
    };
  }

  initializePolyline() {
    // Create our tracking Polyline
    let me = this;
    Polyline.create({
      width: 12,
      points: [],
      geodesic: true,
      color: '#2677FF'
    }, function(polyline) {
      me.polyline = polyline;
    });
  }

  onClickMenu () {
    this.props.drawer.open();
  }

  onClickEnable() {
    let me = this;
    if (!this.state.enabled) {
      this.locationManager.start(function() {
        me.initializePolyline();
      });
    } else {
      this.locationManager.resetOdometer();
      this.locationManager.stop();
      this.setState({
        markers: [{}],
        odometer: 0
      });
      this.setState({
        markers: []
      });
      if (this.polyline) {
        this.polyline.remove(function(result) {
          me.polyline = undefined;
        });
      }
    }

    this.setState({
      enabled: !this.state.enabled
    });
    this.updatePaceButtonStyle();
  }

  onClickPace() {
    if (!this.state.enabled) {
      return;
    }
    let isMoving = !this.state.isMoving;
    this.locationManager.changePace(isMoving);

    this.setState({
      isMoving: isMoving
    });
    this.updatePaceButtonStyle();
  }

  onClickLocate() {
    let me = this;

    this.locationManager.getCurrentPosition({
      timeout: 30
    }, function(location) {
      me.setCenter(location);
    }, function(error) {
      console.error('ERROR: getCurrentPosition', error);
      me.setState({
        navigateButtonIcon: 'navigate'
      });
    });
  }

  onRegionChange() {}

  setCenter(location) {
    this.setState({
      navigateButtonIcon: 'navigate',
      center: {
        lat: location.coords.latitude,
        lng: location.coords.longitude
      },
      zoom: 16
    });
  }

  onLayout() {
    let me = this,
      gmap = this.refs.gmap;

    this.refs.workspace.measure(function(ox, oy, width, height, px, py) {
      me.setState({
        mapHeight: height,
        mapWidth: width
      });
    });
  }

  updatePaceButtonStyle() {
    let style = commonStyles.disabledButton;
    if (this.state.enabled) {
      style = (this.state.isMoving) ? commonStyles.redButton : commonStyles.greenButton;
    }
    this.setState({
      paceButtonStyle: style,
      paceButtonIcon: (this.state.enabled && this.state.isMoving) ? 'Stop Trip' : 'Start Trip'
    });
  }

  render() {
    return (
      <View style={commonStyles.container}>
        <View style={commonStyles.topToolbar}>
          <Icon.Button name="android-options" onPress={this.onClickMenu.bind(this)} backgroundColor="transparent" size={30} color="#000" style={styles.btnMenu} underlayColor={"transparent"} />
          <Text style={commonStyles.toolbarTitle}>Background Geolocation</Text>
          <SwitchAndroid onValueChange={this.onClickEnable.bind(this)} value={this.state.enabled} />
        </View>
        <View ref="workspace" style={styles.workspace} onLayout={this.onLayout.bind(this)}>

          <RNGMap
            ref={'gmap'}
            style={{width: this.state.mapWidth, height: this.state.mapHeight}}
            markers={this.state.markers}
            zoomLevel={this.state.zoom}
            onMapChange={(e) => console.log(e)}
            onMapError={(e) => console.log('Map error --> ', e)}
            center={this.state.center} />

        </View>
        <View style={commonStyles.bottomToolbar}>
          <Icon.Button name={this.state.navigateButtonIcon} onPress={this.onClickLocate.bind(this)} size={25} color="#000" underlayColor="#ccc" backgroundColor="transparent" style={styles.btnNavigate} />
          <Text style={{fontWeight: 'bold', fontSize: 18, flex: 1, textAlign: 'center'}}>{this.state.odometer} km</Text>
          <Button raised={true} 
                  text={this.state.paceButtonIcon} 
                  onPress={this.onClickPace.bind(this)}
                  overrides={{backgroundColor:"#e12429",textColor:"#ffffff"}} 
                  style={this.state.paceButtonStyle}></Button>
          <Text>&nbsp;</Text>
        </View>
      </View>
    );
  }
};

const styles = StyleSheet.create({
  workspace: {
    flex: 1
  }
});

module.exports = Map;

UPDATE: debugging via adb in the terminal shows the same error 更新:通过终端中的adb调试显示相同的错误 安慰

So here is rest of code. 所以这里是其余的代码。 to troubleshoot. 解决。 I added the project files to a plunker. 我将项目文件添加到了插件。 it is a demo project that i am working with. 这是我正在处理的演示项目。 plunker 矮人

    'use strict';

const React = require('react-native');
const {
  Text, 
  Component,
  StyleSheet, 
  AppRegistry
} = React;

import Map from './map/map';
import Drawer from 'react-native-drawer';
import Settings from './settings/settings.android';
import Icon from 'react-native-vector-icons/Ionicons';
import BackgroundGeolocation from 'react-native-background-geolocation-android';

global.bgGeo = BackgroundGeolocation;

class App extends Component {
  onClickMenu() {
    this.props.refs.drawer.open();
  }

  render() {
    return (
      <Drawer ref="drawer" side="right" acceptPan={false} content={<Settings drawer={this.refs.drawer} locationManager={BackgroundGeolocation} />}>
        <Map drawer={this.refs.drawer} locationManager={BackgroundGeolocation} />    
      </Drawer>
    );
  }
};

module.exports = App;

UPDATE: 更新: 屏幕截图

I dont think you can pass through refs to components in such a way, certainly it would not work in React and I dont think it would work in such a way in React-Native either. 我不认为您可以通过这种方式将引用传递给组件,当然它在React也不起作用,我也不认为它在React-Native也如此。

I'm not clear why you are trying to .open the Drawer from the Map component as it looks like the Map component can only be accessed when the Drawer is open, but, if you want to access parent behaviours from children a good pattern is to pass through functions for children to execute (you could argue that this is actually bad and that passing events around is a more robust pattern). 我不明白为什么你想.openDrawerMap部分,因为它看起来像Map部件仅能够访问时, Drawer是打开的,但是,如果你想从孩子父母访问行为的良好格局是传递函数供孩子执行(您可能会说这实际上是不好的,传递事件是更可靠的模式)。

I've never used the library so I'm not totally clear on its usage but you can pass functions through like this: 我从未使用过该库,因此我对其用途尚不完全清楚,但是您可以像这样传递函数:

class Application extends Component {

  closeControlPanel = () => {
    this.refs.drawer.close()
  };
  openControlPanel = () => {
    this.refs.drawer.open()
  };
  render () {
    return (
      <Drawer
        ref="drawer"
        content={<ControlPanel />}
        >
        <Map onMenuClose={ this.closeControlPanel.bind( this ) } />
      </Drawer>
    )
  }
})

In this case this.props.onMenuClose should be attached to an action, which, when executed will trigger the function from the parent and execute the this.refs.drawer.close function. 在这种情况下, this.props.onMenuClose应该附加到一个动作上,该动作在执行时将触发父this.refs.drawer.close功能并执行this.refs.drawer.close函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM