微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

React-Native 自定义Button 获取远程数据

src/component/Button.js

import React,{Component} from 'react';

import {
StyleSheet,
Text,
TouchableOpacity
} from 'react-native';

export default class Button extends Component {
constructor(props) {
super(props);
this.state = {
disabled: false,
};
}

onPress = () => {
const { onPress } = this.props;
//onPress(); //控制按钮的状态方式一
onPress(this.enable); //控制按钮的状态方式二 异步传递一个方法但不立即执行
};

enable = () => {
this.setState({
disabled: false,
});
};

disable = () => {
this.setState({
disabled: true,
});
};

render() {
const { text } = this.props;
return (
<TouchableOpacity
disabled={this.state.disabled}
style={[styles.button,this.state.disabled && styles.disabled]}
onPress={this.onPress}>
<Text style = {styles.buttonText}>{text}</Text>
</TouchableOpacity>
);
}

}

const styles = StyleSheet.create({
button: {
marginTop: 100,
height: 40,
width: 200,
borderRadius: 20,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'green',
},
buttonText: {
fontSize: 16,
color: 'white',
disabled: {
backgroundColor: 'gray',
});

App.js

import React,{Component} from 'react';

import {
StyleSheet,
View
} from 'react-native';

import Button from './src/component/Button';

export default class App extends Component {
constructor(props){
super(props);
this.state = {
title: ''
};
}

//fetchData = () => { //控制按钮的状态方式一 不使用回调参数
fetchData = (enableCallback) => { //控制按钮的状态方式二 使用回调参数
this.refs.button.disable();
fetch('https://facebook.github.io/react-native/movies.json')
//.then((response) => response.json())
.then((response) => response.text())
.then((jsondata) => {
this.setState({
//title: jsondata.movies[1].title,
title: jsondata,
})
})
.catch((error) => {
console.warn(error);
});
this.timer = setTimeout(() => {
//this.refs.button.enable(); //控制按钮的状态方式一
enableCallback(); //控制按钮的状态方式二 执行回调传过来的方法
},5000);

};

componentwillUnmount() {
// 请注意Un"m"ount的m是小写

// 如果存在this.timer,则使用clearTimeout清空。
// 如果你使用多个timer,那么用多个变量,或者用个数组来保存引用,然后逐个clear
this.timer && clearTimeout(this.timer);
}

render() {
return(
<View style={styles.container}>
<Button ref="button" onPress={this.fetchData} text="提交" />
<Text style={styles.instructions}>
{this.state.title}
</Text>
</View>
);
}
}

const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 10,
fontSize: 25,
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐