首页 > 解决方案 > Style a TextInput on React Native every time it is focused

问题描述

I need to style (make bottom border blue) an input each time its focused.

Focus on first input

Focus on fourth input

I have this code on each one.

<Input
    pointerEvents="auto" 
    maxLength={1}
    editable={true}
    secureTextEntry
    style={!this.state.focus ? styles.blueBorder : styles.pinItem }
    onFocus={(e) => this.changeBorder(e, this)}
    name={0}
/>

changeBorder function:

changeBorder (e, v)  {
    !this.state.focus ? this.setState({
            focus: true
        }) : this.setState({
            focus: false
    })
}

styles:

pinItem: {
    marginHorizontal: 8,
    borderWidth: 1,
    borderColor: "#E5E5EA",
    elevation: 3,
    fontSize: 24,
    textAlign: "center",
    height: 58,
    width: 58,
},
blueBorder: {
    marginHorizontal: 8,
    borderWidth: 1,
    borderColor: "#E5E5EA",
    elevation: 3,
    fontSize: 24,
    textAlign: "center",
    height: 58,
    width: 58,
    borderBottomColor: "#0093D7",
    borderBottomWidth: 4,
},

So my inputs act like as follows:

Click on one input

Click on another input

As you can see, that code styles all the components each time some of them are focused. For style them separately I tried using some kind of id for each input so I can set an state object and styled them separately but I couldn't do it. I also tried to use css style for each one using some kind of css pseudo class like focus, but it also didn't work.

I'm pretty new on RN so I can't think on more ways to solve this issue. Thanks in advance for your responses.

PS: I'm using native-base components.

标签: cssreact-native

解决方案


我处理这个问题的方法是将当前聚焦的输入存储在状态中:

constructor(props) {
    super(props);

    this.state = {
        pinFocus: null,
    }
}

然后添加一个获取输入样式的方法:

pinInputStyles(focused = false){
    let styles = [baseStyles];
    if(focused === true){
        styles.push({borderColor: '#000'});
    }
    return styles;
}

然后在输入中,您针对样式、焦点和模糊执行以下三项操作(我已关闭其他属性):

<Input
    style={this.pinInputStyles(this.state.pinFocus === 1)}
    onBlur={ () => this.setState({pinFocus:null}) }
    onFocus={ () => this.setState({pinFocus:1}) }
/>

然后,您将 1 增加到 2、3、4 等以用于其他输入。


推荐阅读