Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära TextInput and Button | Core Components
React Native Fundamentals

TextInput and Button

Svep för att visa menyn

React Native provides interactive components that let you build dynamic, user-friendly apps. Two of the most essential are TextInput and Button. The TextInput component is used to capture user input, such as typing a name, email, or password. The Button component lets users trigger actions, such as submitting a form or saving information. Together, these components form the backbone of most forms and interactive screens in React Native apps.

To see how these components work together, consider a simple form where you ask the user to enter their name and submit it. The TextInput allows the user to type their name, and the Button triggers a function when pressed. In React Native, you manage the input value using state, and respond to button presses with functions.

Here is an example:

import React, { useState } from 'react';
import { View, TextInput, Button, Text } from 'react-native';

export default function NameForm() {
  const [name, setName] = useState('');
  const [submittedName, setSubmittedName] = useState('');

  const handlePress = () => {
    setSubmittedName(name);
  };

  return (
    <View style={{ padding: 20 }}>
      <Text>Enter your name:</Text>
      <TextInput
        value={name}
        onChangeText={setName}
        placeholder="Type your name"
        style={{
          height: 40,
          borderColor: 'gray',
          borderWidth: 1,
          marginBottom: 10,
          paddingHorizontal: 8,
        }}
      />
      <Button
        title="Submit"
        onPress={handlePress}
      />
      {submittedName ? (
        <Text style={{ marginTop: 10 }}>Hello, {submittedName}!</Text>
      ) : null}
    </View>
  );
}

In this code, useState creates two pieces of state: one for the current input value (name) and one for the submitted name (submittedName). The TextInput displays the current value and updates it with onChangeText. The Button calls the handlePress function when pressed, which updates the submittedName. After submission, a greeting message appears using the submitted name. This pattern is common in React Native apps for handling forms and user actions.

question mark

Which component is used to capture user input in React Native?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 2. Kapitel 3

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 2. Kapitel 3
some-alt