问题描述
在反应原生文本输入占位符中,有没有办法为占位符文本提供多种颜色。 电子邮件[黑色] 星号[红色]
我尝试过文本输入的 placeholdertextcolor 属性。但它只允许整个占位符文本使用一种颜色。
解决方法
您可以将自己的占位符组件包装在 TextInput 组件中。它看起来与此类似
<TextInput
value={value}
isFocused={isFocused}
onFocus={() =>
this.setState({ isFocused: true },() => onFocus && onFocus())
}
onBlur={() => this.setState({ isFocused: false })}
>
{!isFocused && !value && (
<Text>
Placeholder Text<Text style={{ color: 'red' }}>*</Text>
</Text>
)}
</TextInput>
确保跟踪输入组件的焦点状态,以便您可以显示占位符或否。
,如上一条评论中所述,您可以添加自定义占位符, 您还可以将其传递给状态并在使用 onResponderStart 按下文本输入时将其清除,这是完整示例:
const example = () => {
const [placeHolderText,setPlaceHolderText] = React.useState('PlaceHolder');
const [placeHolderOtherText,setPlaceHolderOtherText] = React.useState('*');
return (
<View style={{flex: 1,alignContent: 'center',justifyContent: 'center'}}>
<TextInput
//remove placeholder on touching
onResponderStart={() => {
setPlaceHolderOtherText('');
setPlaceHolderText('');
}}>
<Text>
{placeHolderText}
<Text style={{color: 'red'}}>{placeHolderOtherText}</Text>
</Text>
</TextInput>
</View>
);
};