【问题标题】:Alert shows message without pressing Alert Button警报显示消息而不按警报按钮
【发布时间】:2019-04-01 09:40:06
【问题描述】:

我正在使用此代码通过按下按钮来显示我的输入值。但是,每当我输入文本时,只要我向 组件键入任何输入,它就会自动显示一个警告框。

当我按下“添加用户”按钮时,我想显示警报框。它有什么问题?

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


export default class myTest extends Component{
  constructor(){
    super();
    this.state = {firstName: 'your name', lastName: 'your last', email: 'enter your email'};
  }
  onPressButton(){
    let firstName = this.state.firstName;
    let lastName = this.state.lastName;

    Alert.alert("You've Entered" + firstName+"\n "+lastName+"\n");
  }

  render()
  {


      return (
          <View>
            <Text>ENTER YOUR DETAILS:</Text>
            <TextInput
          style={{height: 40}}
          placeholder="FirstName"
          onChangeText={(firstName) => this.setState({firstName})}
        />
           <TextInput
          style={{height: 40}}
          placeholder="Last Name"
          onChangeText={(lastName) => this.setState({lastName})}
        />
        <Text style={{padding: 10, fontSize: 30}}>
          firstName: {this.state.firstName}{'\n'}
          lastName: {this.state.lastName} 
        </Text>
        <Button title="Add User" onPress={this.onPressButton()}/>

          </View>
      );
  }
  }

【问题讨论】:

    标签: react-native react-native-android


    【解决方案1】:

    在 Button 标签内,将 onPress = {this.onPressButton()} 替换为 onPress = {() =&gt; this.onPressButton()}

    【讨论】:

    • 谢谢我正在尝试这样的事情。但我知道我做错了什么
    • 不需要在每次渲染上创建一个新的匿名函数,因为你没有传递任何参数。这样就可以了:onPress = {this.onPressButton}
    • @ErikHaiderForsén 抱歉,我在之前发布过这个问题时尝试过你的版本,但没有成功
    猜你喜欢
    • 2018-05-07
    • 2020-09-11
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多