如何在不重新渲染的情况下更改图标的颜色(TextField失去焦点)

时间:2018-08-20 18:11:58

标签: reactjs react-native

我正在使用名为react-native-phone-input的程序包,更改电话号码后,它将运行功能this.updateInfo(),该功能会更新状态。在我的代码中,图标颜色取决于状态,并且会根据电话号码是否有效而变化。但是,这是可行的,因为状态更改后,由于文本字段失去焦点,因此屏幕会重新呈现,并且键盘会关闭。有没有其他方法可以更改图标颜色?还是有办法让我专注于文本字段?

这是我指的是

enter image description here

import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, TextInput, Keyboard} from 'react-native';
import { Icon } from 'react-native-elements';

import KeyboardAccessory from 'react-native-sticky-keyboard-accessory';
import PhoneInput from 'react-native-phone-input';

export default class PhoneLogin extends Component {

    constructor() {
        super();

        this.state = {
            valid: "",
            type: "",
            value: "",
            iconColor: "#D3D3D3",
        };

        this.updateInfo = this.updateInfo.bind(this);
    }

    updateInfo() {
        this.setState({
            valid: this.phone.isValidNumber(),
            type: this.phone.getNumberType(),
            value: this.phone.getValue().replace(/[- )(]/g,''),
        });
    }

    render() {
        return (
          <View style={styles.container}>
            <PhoneInput
              ref={ref => {
                this.phone = ref;
              }}
              style={{height: 50, borderColor:'#44c0b9', borderBottomWidth:2}}
              onChangePhoneNumber={ (phone) => {this.updateInfo()} }
            />

            <KeyboardAccessory backgroundColor="#fff">
                <View style={{ alignItems: 'flex-end', padding:10 }}>
                    <Icon
                        raised
                        reverse
                        color={(this.state.valid) ? "#44c0b9" : "#D3D3D3"}
                        name='arrow-right'
                        type='font-awesome'
                        onPress={ Keyboard.dismiss()}
                    />
                </View>
            </KeyboardAccessory>
          </View>
        );
    }

}

let styles = StyleSheet.create({
    container: {
      flex: 1,
      alignItems: "center",
      padding: 20,
      paddingTop: 60
    },
    info: {
      // width: 200,
      borderRadius: 5,
      backgroundColor: "#f0f0f0",
      padding: 10,
      marginTop: 20
    },
    button: {
      marginTop: 20,
      padding: 10
    }
  });

1 个答案:

答案 0 :(得分:1)

在图标的onPress中,您需要发送箭头功能。

图标应该是这样

<Icon 
    raised
    reverse
    color={(this.state.valid) ? "#44c0b9" : "#D3D3D3"
    name='arrow-right'
    type='font-awesome'
    onPress={() => Keyboard.dismiss()}
/>

问题在于,每次重新渲染组件时,Keyboard.dismiss()立即运行,从而关闭了键盘。

希望这会有所帮助!