这是React Native无法呈现代码的部分代码:
You input {this.state.zip}.
我是初学者,我正在学习“学习反应原生”的教程但是他在书中的代码不起作用。
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
TextInput,
Image,
View
} from 'react-native';
class WeatherProject extends Component {
// If you want to have a default zip code, you could add one here
getInitialState() {
return ({
zip: ''
});
}
// We'll pass this callback to the <TextInput>
_handleTextChange(event) {
// log statements are viewable in Xcode,
// or the Chrome debug tools
console.log(event.nativeEvent.text);
this.setState({
zip: event.nativeEvent.text
});
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
You input {this.state.zip}.
</Text>
<TextInput
style={styles.input}
onSubmitEditing={this._handleTextChange}/>
</View>
);
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
borderWidth: 2,
height: 40
}
});
AppRegistry.registerComponent('WeatherProject', () => WeatherProject);
[enter image description here][1]
答案 0 :(得分:4)
在ES6类中(您正在扩展Component
而非使用createClass
),在构造函数中使用this.state = {zip: ''}
设置初始状态。
所以它会是
class WeatherProject extends Component {
constructor(props){
super(props);
this.state = {
zip: ""
}
}
}
答案 1 :(得分:1)
getInitialState通常与React.createClass一起使用。要将组件定义为类,以下代码应该在构造函数中:
getInitialState() {
return ({
zip: ''
});
}
构造
constructor() {
super();
this.state = {
zip: ''
}
}