- React Native Cookbook
- Dan Ward
- 226字
- 2025-04-04 14:57:29
How it works...
In step 8, we defined the TextInput component. In React (and React Native), we can use two types of input: controlled and uncontrolled components. In this recipe, we're using controlled input components, as recommended by the React team.
A controlled component will have a value property, and the component will always display the content of the value property. This means that we need a way to change the value when the user starts typing into the input. If we don't update that value, then the text in the input won't ever change, even if the user tries to type something.
In order to update the value, we can use the onChangeText callback and set the new value. In this example, we are using the state to keep track of the data and we are setting a new key on the state with the content of the input.
An uncontrolled component, on the other hand, will not have a value property assigned. We can assign an initial value using the defaultValue property. Uncontrolled components have their own state, and we can get their value by using an onChangeText callback, just as we can with controlled components.