I'm having some problems while I use this implementation:
export default function App() {
const [text, setText] = useState("");
const onChangeText = useCallback((t) => setText(t), []);
const Input = () => {
return (
<TextInput
value={text}
placeholder="dioporco"
style={{ fontSize: 50 }}
onChangeText={onChangeText}
/>
);
};
return (
<View style={styles.container}>
<Input />
</View>
);
}
Whenever I try to write something inside text input, after I've typed one letter the keyboard is dismissed. And this doesn't happen if, instead of , I use {Input()}.
Why this happens? What's the difference? Tank you.
CodePudding user response:
Because each time you enter a character, you will update state, and on updating state, component rerender too.
You have a function for creating TextInput
, when component rerender, function called again, and this cause TextInput rerender too, and react native close keyboard on rerendering.
This is important to not define your component as function in other component.
You can create separated component, or use useMemo
CodePudding user response:
The problem is when you are using functions like that, every time the component is rerendering, it will cause the entire TextInput to be rendered like it didn't exist before. So try to create Input component (Function outside of App) and then use it in App component.
export function Input() {
const [text, setText] = useState("")
const onChangeText = useCallback((t) => setText(t), [])
return (
<TextInput
value={text}
placeholder="dioporco"
style={{ fontSize: 50 }}
onChangeText={onChangeText}
/>
)
}
export default function App() {
return (
<View style={styles.container}>
<Input />
</View>
);
}