“未定义不是对象” this.state 未绑定

IT技术 reactjs react-native
2021-05-22 15:27:06

我通过创建的 react-native 组件React.createClass似乎没有this正确绑定关键字,从而阻止我访问this.state. 这是我得到的错误:

错误

代码如下。我没有看到任何与网站上的示例本质上不同的东西,所以我无法弄清楚我做错了什么。我怎样才能解决这个问题?

'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
1个回答

问题是使用 ES6render: () => {箭头会导致 React 在.createClass函数中提供的自动绑定功能不起作用。

render: function() {..如果您不想将代码转换为 ES6 类,只需将其更改为就可以解决问题。

如果您确实将其转换为 ES6 类,请查看

方法遵循与常规 ES6 类相同的语义,这意味着它们不会自动将 this 绑定到实例。您必须明确使用 .bind(this) 或箭头函数 =>。