【问题标题】:Style a TextInput on React Native every time it is focused每次聚焦时在 React Native 上设置 TextInput 样式
【发布时间】:2018-08-27 21:28:50
【问题描述】:

我需要在每次聚焦时设置输入样式(使底部边框变为蓝色)。

我每个都有这个代码。

<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函数:

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

风格:

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,
},

所以我的输入如下所示:

如您所见,每次聚焦时,代码都会设置所有组件的样式。为了分别设置它们的样式,我尝试为每个输入使用某种 id,这样我就可以设置一个状态对象并分别设置它们的样式,但我做不到。我还尝试使用某种 css 伪类(如焦点)为每个样式使用 css 样式,但它也不起作用。

我对 RN 很陌生,所以我想不出更多方法来解决这个问题。提前感谢您的回复。

PS:我使用的是原生组件。

【问题讨论】:

  • 我不是想有解决方案,但我很好奇你用:focus伪类尝试了什么代码。你介意在代码 sn-p 中分享所有这些吗?

标签: css react-native


【解决方案1】:

问题不在focus。如果您没有意识到这一点,您有每个文本输入的保存指示符,即 this.state.focus。

解决方案

最简单的方法是创建多个状态来指示每个文本输入。

希望对您有所帮助!

【讨论】:

    【解决方案2】:

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

    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 等其他输入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-09
      • 2017-08-07
      • 1970-01-01
      • 1970-01-01
      • 2016-04-01
      • 2017-07-11
      • 1970-01-01
      • 2021-11-01
      相关资源
      最近更新 更多