加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:33:22 所属栏目:百科 来源:网络整理
导读: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: f

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读