系統的Button不好看而且不容易擴展,所以在這里使用TouchableOpacity自定義一個Button
import React, {Component} from "react";
import {Text, StyleSheet, TouchableHighlight, TouchableOpacity, View} from "react-native";
export default class Button extends Component {
state = {
status: 1,
disabled:false,
};
/*customPressHandler(){
//不建議這樣定義方法
alert('你按下了按鈕');
}*/
customPressHandler = () => {
//自定義的方法,請使用屬性來定義,這里自定的把this綁定到這個方法上
alert('你按下了按鈕' + this.state.status);
};
onPress = ()=>{
const {onPress } =this.props;
onPress ? onPress():"";
};
enable=()=>{
this.setState({
disabled:false,
})
};
disabled =()=>{
this.setState({
disabled:true,
})
};
render(){
const {name, backgroundColor} = this.props;
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center',marginBottom:50}}>
<TouchableOpacity
disabled={this.state.disabled}
style={[styles.button,
{backgroundColor:backgroundColor?backgroundColor:'green'},
this.state.disabled && styles.disabled]}
onPress={this.onPress}>
<Text style={styles.buttonText}>{name ? name:"確定"}</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
button: {
width: 150,
height: 40,
borderRadius: 20,
backgroundColor: 'green',
justifyContent: 'center',
overflow: 'hidden'
},
buttonText: {
textAlign: 'center'
},
disabled:{
backgroundColor:'gray',
},
});
使用這個自定義的Button
import React, {Component} from "react";
import {Modal, Text, StyleSheet, TouchableHighlight, TouchableOpacity, View} from "react-native";
import Button from "./component/Button";
export default class ModalExample extends Component {
state = {
modalVisible: false,
status: 1
};
setModalVisible(visible) {
this.setState({modalVisible: visible});
}
fetchData=()=>{
//禁用按鈕
this.refs.button.disabled();
this.timer = setTimeout(()=>{
//獲取完數據后啟用按鈕
this.refs.button.enable();
},3000);
};
componentWillUnmount() {
// 請注意Un"m"ount的m是小寫
// 如果存在this.timer,則使用clearTimeout清空。
// 如果你使用多個timer,那么用多個變量,或者用個數組來保存引用,然后逐個clear
this.timer && clearTimeout(this.timer);
}
render() {
return (
<View style={{marginTop: 22}}>
<Button />
<Button name='取消' backgroundColor='red' onPress={()=>{alert("1")}}/>
{/*ref就相當于html中的id,標記和引用組件*/}
<Button ref='button' onPress={this.fetchData}/>
</View>
);
}
}
這里最后一個Button使用了ref,它就相當于html中的id,標記和引用組件,在這里主要是模擬點擊按鈕后網絡請求數據前后的按鈕禁用和啟用
<Button ref='button' onPress={this.fetchData}/>
fetchData=()=>{
//禁用按鈕
this.refs.button.disabled();
this.timer = setTimeout(()=>{
//獲取完數據后啟用按鈕
this.refs.button.enable();
},3000);
};
這個是使用ref來實現的,還可以使用回調方式:
在自定義組件Button中的onPress方法中這樣改寫
onPress = ()=>{
const {onPress } =this.props;
this.disabled();
onPress ? onPress(this.enable):"";
};
然后在使用中的fetchData方法中這樣改寫
fetchData=(enabledCallback)=>{
this.timer = setTimeout(()=>{
//獲取完數據后啟用按鈕
enabledCallback();
},3000);
};
上面的onPress(this.enable)方法中傳入的this.enable會在fetchData中使用enabledCallback接收,然后執行
gif