如何在React Native中使用onFocus更改一个Textinput的borderColor?

时间:2018-01-15 10:22:10

标签: css react-native react-native-android textinput

我正在尝试使用prop onFocus更改单个Textinput元素的borderColor。我正在使用包含两组样式的数组,第一个“styles.textInput”应该是第一个加载的样式。第二个应该只在切换为true时加载,然后它应该加载第二个样式,即“styles.textInputAlt”

现在,两个textInputs的borderColor正在改变。如何确保获得更改的唯一textInput是当前onFocus的那个?

import React, {Component} from 'react';
import  {
  AppRegistry,
  StyleSheet,
  Text,
  TextInput,
  TouchableHighlight,
  View,

} from 'react-native';

export default class Highlight extends Component{
    constructor(){
        super()
        this.state = {
            toggle: false,
        }
    }

    hasFocus(){
        this.setState({
            toggle: !this.state.toggle
        })
    }

    lostFocus(){
        this.setState({
            toggle:this.state.toggle,
        })

    }
    render(){
        return(
            <View style={styles.container}>
                <TextInput 
                    style={[styles.textInput, this.state.toggle && styles.textInputAlt]}
                    onFocus={()=>this.hasFocus()}  
                    onBlur={()=>this.lostFocus()}
                    /> 

                <TextInput
                    style={[styles.textInput, this.state.toggle && styles.textInputAlt]}
                    onFocus={()=>this.hasFocus()}
                    onBlur={()=>this.lostFocus()}

                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',

  },
  textInput: {
    borderColor: '#000',
    borderWidth: 2.0,
    backgroundColor: '#fff',
    height: 40,
    marginLeft: 60,
    marginRight: 60,
    marginBottom: 30,
    padding: 2,
  },
  textInputAlt: {
    borderColor: '#e71636',
  },
  button: {
    height: 50,
    backgroundColor: '#48bbec',
    alignSelf: 'stretch',
    marginTop: 10,
    marginLeft: 60,
    marginRight: 60,
    justifyContent: 'center'
  },
  buttonText: {
    fontSize: 22,
    color: '#FFF',
    alignSelf: 'center'
  }
});

2 个答案:

答案 0 :(得分:1)

解决问题的一种简单方法是使用参数,这是一个非常基本的例子:

        vv.getRenderContext().setEdgeShapeTransformer(new Function<String, Shape> () {
            @Override
            public Shape apply(String edge) {
                Pair<String> endpoints = graph.getEndpoints(edge);
                float controlY = 60.f;
                 // use some hacked 'ordering' of the endpoint nodes so that the curve for A->B is on the same side as the curve from B->A
                if (endpoints.getFirst().toString().compareTo(endpoints.getSecond().toString()) < 0) {
                    controlY *= -1;
                }
                return new QuadCurve2D.Float(0.0f, 0.0f, 0.5f, controlY, 1.0f, 0.0f);
            }
        });

答案 1 :(得分:0)

您的代码虽然正确,但有一个问题。您正在跟踪是否有任何文本输入被聚焦,但是您应该单独跟踪this.state.toggle每个文本输入(如果愿意,可以选择toggle1和toggle2)。因此,当您关注任何应用程序更新状态时,由于两个文本输入根据this.state.toggle确定其颜色,因此它们都会更改颜色。