加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – “undefined不是一个对象”this.state没有受到约束

发布时间:2020-12-15 20:15:37 所属栏目:百科 来源:网络整理
导读:我通过React.createClass创建的react-native组件似乎没有正确绑定this关键字,阻止我访问this.state.这是我得到的错误: 代码如下.我没有看到与网站上的例子有本质上的不同,所以我无法弄清楚我做错了什么.我怎样才能解决这个问题? 'use strict';var React =
我通过React.createClass创建的react-native组件似乎没有正确绑定this关键字,阻止我访问this.state.这是我得到的错误:

error

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

'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',marginBottom: 10,marginTop: 10,alignSelf: 'stretch',justifyContent: 'center'
  },});

module.exports = Main

解决方法

问题是在渲染中使用ES6胖箭头:()=> {这将导致React在.createClass函数中提供的自动调整功能无法正常工作.

只需将其更改为渲染:如果您不想将代码转换为ES6类,则函数(){..应该可以解决问题.

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

Methods follow the same semantics as regular ES6 classes,meaning that they don’t automatically bind this to the instance. You’ll have to explicitly use .bind(this) or arrow functions =>.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读