css - 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.
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:
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.
解决方案
我处理这个问题的方法是将当前聚焦的输入存储在状态中:
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 等以用于其他输入。
推荐阅读
- php - 为什么我在我的 PHP 中两次获得相同的列?PostgreSQL 查询?
- r - 使用主成分构建分数图
- nginx - Kubernetes(然后是牧场主)超时
- r - 对列名以特定字符串 (R) 结尾的列中的行求和
- angular - “MinValidator”既不是“ComponentType”也不是“DirectiveType”
- c++ - 两个代码有什么区别:for(auto x : v) 和 for(auto& x : v)
- flutter - 如何在 Flutter 的 ListView 中的某个点找到项目?
- c# - 未找到 Microsoft.NetCore.App 或 Microsoft.AspNetCore.App 的指定版本
- node.js - NPM:运行并行脚本时如何读取进程参数?
- docker - 在单个 docker 中连接服务