“未定义不是对象"this.state 没有被绑定 [英] "undefined is not an object" this.state not getting bound
问题描述
我通过 React.createClass
创建的 react-native 组件似乎没有正确绑定 this
关键字,从而阻止我访问 this.state
.这是我得到的错误:
My react-native component, which I'm creating via React.createClass
, does not seem to be binding the this
keyword correctly, preventing me from accessing this.state
. Here's the error I get:
代码如下.我没有看到任何与网站上的示例本质上不同的东西,所以我无法弄清楚我做错了什么.我该如何解决这个问题?
And the code is below. I don't see anything essentially different from the examples on the website, so I can't figure out 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
推荐答案
问题是 render: () => 中使用了 ES6 粗箭头{
这将导致 React 在 .createClass
函数中提供的自动绑定功能不起作用.
The problem is the use of the ES6 fat arrow in render: () => {
that will cause the autobind features that React supplies in the .createClass
function not to work.
如果您不想将代码转换为 ES6 类,只需将其更改为 render: function() {..
即可.
Simply changing this to render: function() {..
should do the trick if you don't want to convert your code to ES6 classes.
如果您确实将其转换为 ES6 类,请查看 这个
If you do convert it to ES6 classes, take a look at this
方法遵循与常规 ES6 类相同的语义,这意味着他们不会自动将 this 绑定到实例.你必须明确使用 .bind(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 =>.
这篇关于“未定义不是对象"this.state 没有被绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!