自定义方法时最好不要向下面哪种定义
customPressHandler(){
//不建议这样定义方法
alert('你按下了按钮');
}
最好使用属性来定义,这样会把this绑定到这个方法上
customPressHandler =()=>{
alert('你按下了按钮'+this.state.status);
};
完整代码:
import React, {Component} from "react";
import {Modal, Text, StyleSheet, TouchableHighlight, TouchableOpacity, View} from "react-native";
export default class ModalExample extends Component {
state = {
modalVisible: false,
status: 1
};
setModalVisible(visible) {
this.setState({modalVisible: visible});
}
/*customPressHandler(){
//不建议这样定义方法
alert('你按下了按钮');
}*/
customPressHandler = () => {
//自定义的方法,请使用属性来定义,这里自定的把this绑定到这个方法上
alert('你按下了按钮' + this.state.status);
};
render() {
return (
<View style={{marginTop: 22}}>
<Modal
animationType="slide"
transparent={false}
presentationStyle="overFullScreen"
visible={this.state.modalVisible}
onRequestClose={() => {
alert("Modal has been closed.");
}}
>
<View style={{marginTop: 22}}>
<View>
<Text>Hello World!</Text>
<TouchableOpacity
onPress={() => {
this.setModalVisible(!this.state.modalVisible);
}}
>
<Text>Hide Modal</Text>
</TouchableOpacity>
</View>
<Text>这是测试内容</Text>
</View>
</Modal>
<TouchableHighlight
onPress={() => {
this.setModalVisible(true);
}}
>
<Text>Show Modal</Text>
</TouchableHighlight>
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<TouchableOpacity
style={styles.button}
onPress={this.customPressHandler}>
<Text style={styles.buttonText}>确定</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
button: {
width: 150,
height: 40,
borderRadius: 20,
backgroundColor: 'green',
justifyContent: 'center',
overflow: 'hidden'
},
buttonText: {
textAlign: 'center'
}
});