react native 基础按钮的组件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react native 基础按钮的组件相关的知识,希望对你有一定的参考价值。
/**
* Created by zmis2 on 2016/11/18.
*/
import React,{Component} from ‘react‘;
import {
Text,
View,
StyleSheet,
TouchableOpacity,
} from ‘react-native‘;
export default class Button extends Component {
//构造
constructor(props) {
super(props);
//初始状态
this.state = {
disabled: false
};
}
onPress = () => {
const {onPress} = this.props;
onPress();
};
enable = () => {
this.setState({
disabled: false
})
};
disable = () => {
this.setState({
disabled: true
})
};
render() {
//解构
const {test,bgc} = this.props;
return (
<TouchableOpacity
disabled={this.state.disabled}//禁用按钮
style={[styles.button,{backgroundColor: bgc},this.state.disabled && styles.disabled]}
onPress={this.onPress}
>
<Text style={styles.buttonText}>{this.props.text}</Text>
</TouchableOpacity>
)
}
}
const styles = StyleSheet.create({
button: {
height:40,
width:120,
borderRadius:20,
justifyContent: ‘center‘
},
buttonText: {
textAlign: ‘center‘,
color: ‘red‘
},
disabled: {
backgroundColor: ‘gray‘
}
});
调用组件,禁用,重启按钮
import React,{Component} from ‘react‘;
import {
Text,
View,
Image,
AppRegistry,
StyleSheet,
TouchableOpacity,
} from ‘react-native‘;
import Button from ‘./src/component/Button‘;
class First extends Component {
fetchData = () => {
this.refs.button.disable();//按后禁用按钮
this.timer = setTimeout( () => {
this.refs.button.enable();
},3000);//3S启用按钮
};
componentWillUnmount() {
this.timer && clearTimeout(this.timer);//清除计数器
}
render() {
return (
<Image source={require(‘./img/bg.png‘)}>
<View style={styles.container}>
{/*ref就相当于html的id,标记和引用组件*/}
<Button ref="button" text="Let‘s Start" bgc="yellow" onPress={this.fetchData}/>
</View>
</Image>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop:400,
marginLeft:50
}
});
以上是关于react native 基础按钮的组件的主要内容,如果未能解决你的问题,请参考以下文章
Wix React-Native-Navigation:自定义组件按钮的 onPress
React Native ScrollView - 如何从另一个子组件按钮滚动到子组件?
ReactNative进阶(十九):React Native按钮Touchable系列组件使用详解