在 Focus React Native 上更改 TextInput 样式

Raw*_*awr 2 android textinput reactjs 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}
  />
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Sha*_*rza 5

使用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'}} 
 />
Run Code Online (Sandbox Code Playgroud)

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