react native button 按钮

用react native自定义一个button按钮

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

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    TouchableOpacity
} from 'react-native';

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

    onPress_() {
        if (typeof this.props.onPress === 'function') {
            this.props.onPress();
        }
    }

    setDisabled_(yes) { this.setState({disabled: yes}); }
    isDisabled_() { return this.state.disabled; }

    setText_(text) { this.setState({text: text}); }
    text_() { return this.state.text; }

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

styles = StyleSheet.create({
    button: {
        backgroundColor:'#0c3ba9',
        width: 80,
        height: 40,
        justifyContent: 'center',
        borderRadius: 10,
        overflow: 'hidden',
    },
    text: {
        textAlign: 'center',
        color: '#fff',
        fontSize: 16,
    },
    disabled: {
        backgroundColor: '#999999'
    }
})

测试代码

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TextInput
} from 'react-native';
import Button from '../common/Button.js'

export default class ButtonTest extends Component {

  onToggle_() {
    this.refs.okButton.setDisabled_(!this.refs.okButton.isDisabled_());
  }

  render() {
    return (
      <View style={styles.container}>
        <Button ref="okButton" text="确定" onPress={()=>{alert(this.refs.okButton.text_())}} />
        <Button text="切换状态" onPress={this.onToggle_.bind(this)} />
        <TextInput style={styles.textInput} placeholder="改变确定按钮文本" onChangeText={(text) => this.refs.okButton.setText_(text)} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  textInput: {
    width: 130,
  }
});

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值