"undefined is not an object" this.state unrelated

My response component, which I create with React.createClass, does not seem to bind the keyword thiscorrectly, preventing me from accessing this.state. Here is the error I get:

error

And the code is below. I do not see anything fundamentally different from the examples on the website, so I cannot understand what I'm doing wrong. How can i fix this?

'use strict';

var React = require('react-native');

var Main = React.createClass({
  getInitialState: () => {
    return { username: '', isloading: false, iserror: false };
  },
  handleChange: (event) => {
    this.setState({
      username: event.nativeEvent.text
    });
  },
  handleSubmit: (event) => {
    this.setState({
      isloading: true
    });
    console.log('Submitting... ' + this.state.username);
  },
  render: () => {
    return (
      <View style={styles.mainContainer}>
        <Text> Search for a Github User</Text>
        <TextInput style={styles.searchInput}
                   value={this.state.username}
                   onChange={this.handleChange.bind(this)} /> 
        <TouchableHighlight style={styles.button}
                            underlayColor='white'
                            onPress={this.handleSubmit.bind(this)} /> 
        <Text style={styles.buttonText}> SEARCH</Text>
      </View>
    );
  }
});

var { Text, View, StyleSheet, TextInput, TouchableHighlight, ActivityIndicatorIOS } = React;

var styles = StyleSheet.create({
  mainContainer: {
    flex: 1,
    padding: 30,
    marginTop: 65,
    flexDirection: 'column',
    justifyContent: 'center',
    backgroundColor: '#48BBEC'
  },
  title: {
    marginBottom: 20,
    fontSize: 25,
    textAlign: 'center',
    color: '#fff'
  },
  searchInput: {
    height: 50,
    padding: 4,
    marginRight: 5,
    fontSize: 23,
    borderWidth: 1,
    borderColor: 'white',
    borderRadius: 8,
    color: 'white'
  },
  buttonText: {
    fontSize: 18,
    color: '#111',
    alignSelf: 'center'
  },
  button: {
    height: 45,
    flexDirection: 'row',
    backgroundColor: 'white',
    borderColor: 'white',
    borderWidth: 1,
    borderRadius: 8,
    marginBottom: 10,
    marginTop: 10,
    alignSelf: 'stretch',
    justifyContent: 'center'
  },
});

module.exports = Main
+4
source share
1 answer

The problem is using the ES6's fat arrow render: () => {, which will cause the autodiscover functions that may be involved in the function .createClassto not work.

render: function() {.. , ES6.

ES6, this

, ES6, , . .bind() = > .

+9

Source: https://habr.com/ru/post/1623207/


All Articles