[英]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);
那么你可以使用setState
或useState
來改變樣式。
這是使用鈎子的另一種方法(我正在使用 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.