【问题标题】:How to get a text input value in a view?如何在视图中获取文本输入值?
【发布时间】:2020-11-17 13:49:47
【问题描述】:

我正在研究 React Native,我是一个初学者,如果我的问题特别简单,请提前抱歉。

我目前在视图 (Home.Js) 中工作,而不是在 App.Js 中工作。在这个主页视图中,我有一个文本输入(用户名),我想获取用户单击按钮时输入的值。我观看了解释视频,但他们解释了如何在 App.Js 中执行此操作,当我在我的视图中实现它时它不起作用。这是我的代码。谢谢


#Here We Are in my Home View (Home.Js) not App.Js

import React from 'react';
import { Image, ImageBackground, StyleSheet, View, Text, TouchableOpacity, TextInput, Button } from 'react-native';

function Home(props) {

return (
    <View style={styles.container}>
        <View style={styles.header}>
            <Image source={require('../assets/logo.png')}
            style={styles.Logo}/>
            <Image source={require('../assets/Joiny.png')}
            style={styles.Logo}/>
        </View>
        <View style={styles.footer}>
            <TextInput>Username</TextInput>
        </View>

    </View>
);

};

【问题讨论】:

    标签: react-native view textinput


    【解决方案1】:

    试试这个方法

    import React from 'react';
    import { View, Text, TouchableOpacity } from 'react-native';
    
    function Home(props) {
    
    const [text, setText] = useState('');
    
    return (
        <View style={styles.container}>
           ......
            <View style={styles.footer}>
                <TextInput onChangeText={text => setText(text)}>Username</TextInput>
            </View>
            <TouchableOpacity onPress={() => alert(TouchableOpacity)}>
                <TextInput onChangeText={text => setText(text)}>Username</TextInput>
            </TouchableOpacity>
    
        </View>
    );
    export default App;
    

    【讨论】:

      【解决方案2】:

      您可以在state 中设置值并在按下按钮时从state 中检索值

      export default function App() {
         const [value, onChangeText] = React.useState('');
        return (
          <View style={styles.container}>
           
          <TextInput
            style={{ height: 40, borderColor: 'gray', borderWidth: 1,marginBottom:30 }}
            onChangeText={text => onChangeText(text)}
            value={value}
            placeholder="Username"
          />
          <Button onPress={() => {
            alert(value)
          }}
        title="Learn More"
        color="#841584" />
        
          </View>
        );
      }
      

      小吃链接https://snack.expo.io/La32SNKz5

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-02
        • 1970-01-01
        • 2018-06-23
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        • 2015-06-30
        • 2015-06-17
        相关资源
        最近更新 更多