TextInputRightButton.js 2.8 KB
'use strict';
import React, {Component} from "react";

import {Image, StyleSheet, TextInput, TouchableOpacity, View,} from "react-native";

import {zoomH, zoomW} from "../../utils/getSize";
import PropTypes from 'prop-types';

export default class TextInputRightButton extends Component {

// 传递参数属性定义
    static PropTypes = {
        onButtonClick: PropTypes.func.isRequired
    }

    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            inputValue: "",
        };
        this.onChange = this._onChange.bind(this);
    }

    _isNull(str) {
         let result = true;
        if (str === "" || str === undefined) {
            result = true;
        }

        if (str.length > 0) {
            result = false;
        }
        return result;
    }


    render() {
        let {inputValue} = this.state;
        return (
            <View style={styles.container}>
                <TextInput
                    underlineColorAndroid="transparent"
                    numberOfLines={1}
                    clearButtonMode={'never'}
                    value={inputValue}
                    onChangeText={this.onChange}
                    {...this.props}/>
                {this._isNull(inputValue) ? null : this._getRightButtonView()}
            </View>
        );
    }

    _getRightButtonView() {
        //右侧按钮图
        //自定义 按钮图
        let source = this.props.source ? this.props.source : require('../../img/input_clear.png');
        return (
            <TouchableOpacity activeOpacity={0.5}
                              style={styles.closeOpacityStyle}
                              onPress={() => {
                                  this.props.onButtonClick();
                              }}>
                <Image style={styles.closeStyle}
                       source={source}/>
            </TouchableOpacity>)
    }

    //清除输入款中的值
    clearInputValue() {
        this.setState({inputValue: ""})
    }

    //获取输入款中的值
    getInputValue() {
        return this.state.inputValue;
    }

    _onChange(changeText) {
        this.setState({
            inputValue: changeText,
        });
    }

}

const styles = StyleSheet.create(
    {
        container: {
            flex: 1,
            flexDirection: 'row',
            alignItems: 'center'
        },
        closeStyle: {
            height: 18/zoomW,
            width: 18/zoomW,
        },
        closeOpacityStyle: {
            height: 54/zoomH,
            width: 54/zoomW,
            justifyContent: 'center',
        },
    }
)
// ---------------------
// 作者:孑书力
// 来源:CSDN
// 原文:https://blog.csdn.net/cjw8990/article/details/79351560
// 版权声明:本文为博主原创文章,转载请附上博文链接!