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,
});

相关文章

一、前言 在组件方面react和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...