React Native - 文字輸入



在本章,我們將展示如何使用 React Native 中的TextInput元素。

Home 元件將匯入並渲染輸入。

App.js

import React from 'react';
import Inputs from './inputs.js'

const App = () => {
   return (
      <Inputs />
   )
}
export default App

輸入

我們將定義初始狀態。

定義好初始狀態後,我們將建立handleEmailhandlePassword函式。這些函式用於更新狀態。

login()函式將警示狀態的當前值。

我們還將向文字輸入新增一些其他屬性以停用大寫鎖定、移除 Android 裝置上的底部邊框,並設定佔位符。

inputs.js

import React, { Component } from 'react'
import { View, Text, TouchableOpacity, TextInput, StyleSheet } from 'react-native'

class Inputs extends Component {
   state = {
      email: '',
      password: ''
   }
   handleEmail = (text) => {
      this.setState({ email: text })
   }
   handlePassword = (text) => {
      this.setState({ password: text })
   }
   login = (email, pass) => {
      alert('email: ' + email + ' password: ' + pass)
   }
   render() {
      return (
         <View style = {styles.container}>
            <TextInput style = {styles.input}
               underlineColorAndroid = "transparent"
               placeholder = "Email"
               placeholderTextColor = "#9a73ef"
               autoCapitalize = "none"
               onChangeText = {this.handleEmail}/>
            
            <TextInput style = {styles.input}
               underlineColorAndroid = "transparent"
               placeholder = "Password"
               placeholderTextColor = "#9a73ef"
               autoCapitalize = "none"
               onChangeText = {this.handlePassword}/>
            
            <TouchableOpacity
               style = {styles.submitButton}
               onPress = {
                  () => this.login(this.state.email, this.state.password)
               }>
               <Text style = {styles.submitButtonText}> Submit </Text>
            </TouchableOpacity>
         </View>
      )
   }
}
export default Inputs

const styles = StyleSheet.create({
   container: {
      paddingTop: 23
   },
   input: {
      margin: 15,
      height: 40,
      borderColor: '#7a42f4',
      borderWidth: 1
   },
   submitButton: {
      backgroundColor: '#7a42f4',
      padding: 10,
      margin: 15,
      height: 40,
   },
   submitButtonText:{
      color: 'white'
   }
})

每當我們在其中一個輸入框中輸入時,狀態都會更新。當我們點選Submit按鈕時,輸入內容將顯示在對話方塊中。

React Native Text Input

每當我們在其中一個輸入框中輸入時,狀態都會更新。當我們點選Submit按鈕時,輸入內容將顯示在對話方塊中。

React Native Text Input
廣告