首先,我通过其他帖子进行了研究并找到了这个How to change styling of TextInput placeholder in React Native?
帖子中解决方案的问题是,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}
/>
我通过强迫TextInput
使用forceUpdate()
更新或者为组件设置了密钥来解决了一些问题,但这导致键盘UI在用户输入时关闭,这对用户体验不利
我想简单评论链接的帖子,但我的声誉还不够。
这是预期的行为还是我犯了什么错误? 如果有人能提供一些解释/解决方案,我们将不胜感激。
P.S。使用最新的React Native
在Android上测试答案 0 :(得分:2)
使用onFocus作为文本输入来处理您的案例。因为每当您关注文本输入并开始键入时,它将更新状态,组件将重新呈现。请查看this expo snack示例用法。
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'}}
/>
了解有关组件生命周期的更多信息,然后您将了解如何处理更多此类案例,并且在使用组件之前始终阅读文档,然后您可以轻松找到适合您特定案例的解决方案。 / p>
答案 1 :(得分:0)
通常,TextInput具有某些公共样式,因此您可以使用Stylesheet.compose来减少代码,如下所示:
cf local run myProject -f myProject -d ~/Development/myProject
然后您可以使用 const styles = StyleSheet.create({
input: {
borderRadius: 5,
},
inputOnFocus: {
borderBottomWidth: 2,
borderBottomColor: 'green'
}
});
const inputOnFocus = StyleSheet.compose(styles.input, styles.inputOnFocus);
或setState
来更改样式。
答案 2 :(得分:0)
这是使用钩子的另一种方式(我正在使用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',
}
})