react native button 按钮

前端之家收集整理的这篇文章主要介绍了react native button 按钮前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

用react native自定义一个button按钮

button代码,响应按下事件,设置获取disabled状态,设置获取显示文本

  1. import React,{ Component } from 'react';
  2. import {
  3. AppRegistry,StyleSheet,Text,View,TouchableOpacity
  4. } from 'react-native';
  5.  
  6. export default class Button extends Component {
  7. constructor(props) {
  8. super(props);
  9. this.state = {
  10. disabled: props.disabled,text: props.text,}
  11. }
  12.  
  13. onPress_() {
  14. if (typeof this.props.onPress === 'function') {
  15. this.props.onPress();
  16. }
  17. }
  18.  
  19. setDisabled_(yes) { this.setState({disabled: yes}); }
  20. isDisabled_() { return this.state.disabled; }
  21.  
  22. setText_(text) { this.setState({text: text}); }
  23. text_() { return this.state.text; }
  24.  
  25. render() {
  26. return (
  27. <TouchableOpacity
  28. style={[styles.button,this.state.disabled && styles.disabled]}
  29. onPress={this.onPress_.bind(this)}
  30. disabled={this.state.disabled} >
  31. <Text style={styles.text}>
  32. {this.state.text}
  33. </Text>
  34. </TouchableOpacity>
  35. )
  36. }
  37. }
  38.  
  39. styles = StyleSheet.create({
  40. button: {
  41. backgroundColor:'#0c3ba9',width: 80,height: 40,justifyContent: 'center',borderRadius: 10,overflow: 'hidden',},text: {
  42. textAlign: 'center',color: '#fff',fontSize: 16,disabled: {
  43. backgroundColor: '#999999'
  44. }
  45. })

测试代码

  1. import React,{ Component } from 'react';
  2. import {
  3. AppRegistry,TextInput
  4. } from 'react-native';
  5. import Button from '../common/Button.js'
  6.  
  7. export default class ButtonTest extends Component {
  8.  
  9. onToggle_() {
  10. this.refs.okButton.setDisabled_(!this.refs.okButton.isDisabled_());
  11. }
  12.  
  13. render() {
  14. return (
  15. <View style={styles.container}>
  16. <Button ref="okButton" text="确定" onPress={()=>{alert(this.refs.okButton.text_())}} />
  17. <Button text="切换状态" onPress={this.onToggle_.bind(this)} />
  18. <TextInput style={styles.textInput} placeholder="改变确定按钮文本" onChangeText={(text) => this.refs.okButton.setText_(text)} />
  19. </View>
  20. );
  21. }
  22. }
  23.  
  24. const styles = StyleSheet.create({
  25. container: {
  26. flex: 1,flexDirection: 'row',justifyContent: 'space-around',alignItems: 'center',backgroundColor: '#F5FCFF',textInput: {
  27. width: 130,}
  28. });

猜你在找的React相关文章