Android 更改焦点上的文本输入样式
首先,我通过其他帖子进行了研究,发现了这一点 文章中的解决方案的问题是,一旦Android 更改焦点上的文本输入样式,android,reactjs,react-native,textinput,Android,Reactjs,React Native,Textinput,首先,我通过其他帖子进行了研究,发现了这一点 文章中的解决方案的问题是,一旦fontStyle设置为斜体,它就不会返回到正常字体(我猜除非组件更新,否则它不能被覆盖)。这是我的代码示例 <TextInput style={ this.state.value.length === 0 ? {fontStyle: 'italic', color: 'white'} // font changed to white and italic : {fo
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关闭,这对用户体验不利
我只想对链接的帖子发表评论,但我的声誉还不够
是故意的还是我犯了什么错误?
如果有人能提供一些解释/解决方案,我们将不胜感激
p.S.使用最新的React Native在Android上测试,用于文本输入以处理您的案例。因为每当您聚焦文本输入并开始键入时,它将更新状态,组件将重新渲染。请看下面的示例用法
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'}}
/>
state={isFocused:false};
onFocusChange=()=>{
this.setState({isFocused:true});
}
因此,了解有关组件生命周期的更多信息,您将知道如何处理更多此类情况,并且在使用组件之前始终阅读文档,这样您将很容易找到针对特定情况的解决方案。通常TextInput具有一些公共样式,因此您可以使用Stylesheet.compose来减少代码,如下所示:
const styles=StyleSheet.create({
输入:{
边界半径:5,
},
输入焦点:{
边界宽度:2,
边框底部颜色:“绿色”
}
});
const inputOnFocus=StyleSheet.compose(styles.input,styles.inputOnFocus);
然后您可以使用
setState
或useState
来更改样式。这里是使用挂钩的另一种方法(顺便说一句,我使用的是expo.io)
import React,{useState}来自“React”
从“react native”导入{View,StyleSheet,TextInput}
常量文本输入=()=>{
常量[isHighlighted,setIsHighlighted]=使用状态(false)
返回(
{Setishighletted(真)}
onBlur={()=>{setishighletted(false)}/>
)
}
const styles=StyleSheet.create({
文本输入:{
边框颜色:“灰色”,
borderWidth:StyleSheet.hairlineWidth,
边界半径:8,
身高:43,
},
石景光:{
边框颜色:“绿色”,
}
})
为什么不按组件状态处理此问题?@ShahzadMirza变量值来自组件状态。我将对其进行编辑以使其更清晰。因此,基本上,您希望以白色显示占位符斜体,一旦用户开始输入值,您希望文本值为黑色,字体为普通字体?对吗?@ShahzadMirza Yes谢谢您的回答和解释。我认为即使在我们键入时,组件也会在每次更新状态时重新呈现。我将再次尝试了解更多关于组件生命周期的信息。作为说明,我还使用onBlur将焦点转到另一个文本输入时的isFocused设置为false。
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',
}
})