如何將具有成員變量的React組件重構爲es6類 它可以在沒有狀態變量的情況下工作。爲什麼在運行下面的代碼時,我會得到一個很大的紅色屏幕,顯示「不能添加屬性計數器,對象不可擴展」?如何使用成員變量對es6類進行重構
'use strict';
let Dimensions = require('Dimensions');
let totalWidth = Dimensions.get('window').width;
let leftStartPoint = totalWidth * 0.1;
let componentWidth = totalWidth * 0.8;
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
TextInput,
View
} from 'react-native';
class Login extends Component {
constructor(props) {
super(props);
this.counter =23;
this.state = {
inputedNum: ''
};
}
updateNum(aEvent) {
this.setState((state) => {
return {
inputedNum: aEvent.nativeEvent.text,
};
});
}
buttonPressed() {
this.counter++;
console.log(':::'+this.counter);
}
render() {
return (
<View style={styles.container}>
<TextInput style={styles.numberInputStyle}
placeholder={'input phone number'}
onChange={(event) => this.updateNum(event)}/>
<Text style={styles.bigTextPrompt}
onPress={this.buttonPressed}>
Press me...
</Text>
</View>
);
}
}
let styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
},
numberInputStyle: {
top: 20,
left: leftStartPoint,
width: componentWidth,
backgroundColor: 'gray',
fontSize: 20
},
bigTextPrompt: {
top: 70,
left: leftStartPoint,
width: componentWidth,
backgroundColor: 'gray',
color: 'white',
textAlign: 'center',
fontSize: 60
}
});
AppRegistry.registerComponent('Project18',() => Login);
爲什麼你不希望變量被存儲在狀態? –
在我的理解中,存儲在狀態中的變量與UI的呈現有關。如果我的變量與用戶界面無關,那麼我不希望將其存儲在狀態中,以免造成不必要的渲染 – tennist
好吧,我已經更新了答案以及示例項目。 –