简体   繁体   中英

Changing text color clears TextInput in react-native

I have tried getting the result in a couple of different ways but i don't know if this is a bug or if i am doing something wrong.

When changing the color in styling of my TextInput the input gets cleared and all text goes away showing only placeholder text .

const [focusInputTextColor, setFocusInputTextColor] = useState("000000");

const onFocusInput = () => {
    setFocusInputTextColor('#ffffff');
};

const onBlurInput = () => {
    setFocusInputTextColor('#000000');
};

<TextInput
    style={[styles.input,{color:focusInputTextColor}]}
    onChangeText={() => console.log("test")}
    placeholder="Placeholder here"
    placeholderTextColor="#000000"
    onFocus={() => onFocusInput()}
    onBlur={() => onBlurInput()}
/>

Am i doing something wrong or is this a bug?

This behavior is likely due to the way you're handling the onChangeText event. The onChangeText event is called every time the text in the TextInput changes, but you're not updating the state with the new text. To fix this issue, try updating the state with the new text in the onChangeText event.


Edit - Q1: It could be because the onBlur event is being triggered before the onChangeText event. You can try updating the state with the input text in the onBlur event to see if that fixes the issue.

Here is an example:

const [inputText, setInputText] = useState("");
const [focusInputTextColor, setFocusInputTextColor] = useState("000000");

const onFocusInput = () => {
setFocusInputTextColor('#ffffff');
};

const onBlurInput = () => {
setFocusInputTextColor('#000000');
setInputText(inputText);
};

<TextInput
style={[styles.input,{color:focusInputTextColor}]}
onChangeText={text => setInputText(text)}
value={inputText}
placeholder="Placeholder here"
placeholderTextColor="#000000"
onFocus={() => onFocusInput()}
onBlur={() => onBlurInput()}
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM