繁体   English   中英

在 Focus React Native 上更改 TextInput 样式

[英]Change TextInput Style on Focus React Native

首先,我研究了其他帖子并找到了这个如何在 React Native 中更改 TextInput 占位符的样式?

帖子中解决方案的问题是,一旦将fontStyle设置为斜体,它就不会恢复为正常字体(我猜除非组件更新,否则它无法被覆盖)。 这是我的代码示例

  <TextInput
    style={
      this.state.value.length === 0
      ? {fontStyle: 'italic', color: 'white'} // font changed to white and italic
      : {fontStyle: 'normal', color: 'black'} // font changed to black but stays italic
    }
    value={this.state.value}
  />

我想出了一些技巧,通过使用forceUpdate()强制TextInput更新或为组件设置一个键,但这会导致键盘 UI 在用户键入时关闭,这对 UX 不利。

我只想对链接的帖子发表评论,但我的声誉还不够。

这是预期的行为还是我犯了任何错误? 如果有人可以提供一些解释/解决方案,将不胜感激。

PS 使用最新的 React Native 在 Android 上测试

使用onFocus作为文本输入来处理您的情况。 因为每当您聚焦文本输入并开始输入时,它都会更新状态并且组件将重新渲染。 使用示例用法查看此博览会小吃

state = { isFocused: false }; 

onFocusChange = () => {
    this.setState({ isFocused: true });
}

<TextInput 
    onFocus={this.onFocusChange}
    placeholder='Enter Input Here'
    style={(this.state.isFocused) ? {fontStyle: 'normal', color: 'black'} : {fontStyle: 'italic', color: 'white'}} 
 />

因此,了解有关组件生命周期的更多信息,您将知道如何处理更多此类情况,并且在使用组件之前始终阅读文档,然后您将轻松找到适合您特定情况的解决方案。

通常 TextInput 有一些公共样式,因此您可以使用 Stylesheet.compose 来减少您的代码,如下所示:

    const styles = StyleSheet.create({
        input: {
            borderRadius: 5,
        },
        inputOnFocus: {
            borderBottomWidth: 2,
            borderBottomColor: 'green'
        }
    });
    
    const inputOnFocus = StyleSheet.compose(styles.input, styles.inputOnFocus);

那么你可以使用setStateuseState来改变样式。

这是使用钩子的另一种方法(我正在使用 expo.io btw)

    import React, { useState } from 'react'
    import { View, StyleSheet, TextInput } from 'react-native'
    
    const TextInput = () => {
      const [isHighlighted, setIsHighlighted] = useState(false)
    
       return (
        <View>
          <TextInput
            style={[styles.textInput, isHighlighted && styles.isHighlighted]}
            onFocus={() => { setIsHighlighted(true)}
            onBlur={() => {setIsHighlighted(false)} />
        </View>
      )
    }
    
    const styles = StyleSheet.create({
      textInput: {
        borderColor: 'grey',
        borderWidth: StyleSheet.hairlineWidth,
        borderRadius: 8,
        height: 43,
      },
      isHighlighted: {
        borderColor: 'green',
      }
    })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM