【问题标题】:Need to implement onPress logic on react native app to perfume two tasks需要在 react native app 上实现 onPress 逻辑来处理两个任务
【发布时间】:2020-02-20 03:59:41
【问题描述】:

嘿 stackoverflow 我是 react native 世界的新手,通过文档和教程学习它。我的问题是我想通过 onPress 在单个按钮上执行两个任务。这是我想要的,我有两页。在第一页用户输入他的电话号码,我将其保存在数据库中。当用户按下验证按钮时,它现在将值插入 DB p>

//mobilecheck.js
import React, { Component } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity, ActivityIndicator, Platform,Button} from 'react-native';

export default class MobileCheck extends React.Component
{

    constructor(){
         super()
         this.state = {
            TextInput_mobile_number: '',
            mobile_number: '', loading: false, disabled: false
    
             
         }
       
    }

    sendDatafun=()=>{
        this.props.navigation.navigate('VerifyCode',{
            mobile_number:this.state.mobile_number
        });

    }
 
    saveData = () =>
    {
        this.setState({ loading: true, disabled: true }, () =>
        {
            fetch('http://192.168.2.186/otplogin/mobile_checkapi.php',
            {
                method: 'POST',
                headers: 
                {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(
                {
                    mobile_number: this.state.mobile_number,
                    
                    
 
                })
 
            }).then((response) => response.json()).then((responseJson) =>
            {
                alert(responseJson);
                this.setState({ loading: false, disabled: false });
            }).catch((error) =>
            {
                console.error(error);
                this.setState({ loading: false, disabled: false });
            });
        });

    }
    
    render()
    {
        const { navigate } = this.props.navigation;
        return(
            <View style = { styles.container }>
                <TextInput underlineColorAndroid = "transparent" placeholder = "Please Enter Your Mobile Number" style = { styles.textInput } onChangeText = {(text) => this.setState({ mobile_number: text })}  
               // onChangeText={data => this.setState({ TextInput_mobile_number: data })}
                keyboardType={'numeric'}
                
                />
                
                <TouchableOpacity disabled = { this.state.disabled } activeOpacity = { 0.8 } style = { styles.Btn } onPress = { this.saveData } onPress={this.sendDatafun}  >
                    <Text style = { styles.btnText }>Get Code</Text>
                    
                </TouchableOpacity>
                <Button title = 'Next'  
                    onPress={this.sendDatafun}
                />
 
                {
                    (this.state.loading)
                    ?
                        (<ActivityIndicator size = "large" />)
                    :
                        null
                }
                
            </View>
        );
    }
}
//verifycode.js
import React, { Component } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity, ActivityIndicator, Platform,Button } from 'react-native';


export default class VerifyCode extends React.Component
{
    constructor(props)
    {
        super(props);
 
        this.state = { 	
            code: '', 
            TextInput_mobile_number: '',
            mobile_number: '',
             
            // new code
            UserName: '',
            UserEmail: '',
            UserPassword: '',
            UserCity: '',

            loading: false, 
            disabled: false,

        }
    }
//     nextbutton = () =>
//   {
//      this.props.navigation.navigate('SignUp');
     
//   }
    
    saveData = () =>
    {

        // new code 
        const { UserName }  = this.state ;
        const { UserEmail }  = this.state ;
        const { UserPassword }  = this.state ;
        const { UserCity }  = this.state ;
        this.setState({ loading: true, disabled: true }, () =>
        {
            fetch('http://192.168.2.186/otplogin/verify_codeapi.php',
            {
                method: 'POST',
                headers: 
                {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(
                {
                    code: this.state.code,
                    mobile_number: this.props.navigation.state.params.mobile_number,

                    //new code
                    user_name: UserName,
    
                    user_email: UserEmail,
                    
                    user_password: UserPassword,

                    user_city: UserCity,
                    
 
                })
 
            }).then((response) => response.json()).then((responseJson) =>
            {
                alert(responseJson);
                this.setState({ loading: false, disabled: false });
            }).catch((error) =>
            {
                console.error(error);
                this.setState({ loading: false, disabled: false });
            });
        });
    }
 
    render()
    {
        return(
            <View style = { styles.container }>

                <Text style={styles.textStyle}>
                We send verification code to : {this.props.navigation.state.params.mobile_number}
                </Text>
                <TextInput underlineColorAndroid = "transparent" placeholder = "Please Enter Your Verification Code" style = { styles.textInput } onChangeText = {(text) => this.setState({code: text })}
                    keyboardType={'numeric'}
                />
                <TextInput
                placeholder="Enter Your Full Name"
                onChangeText={UserName => this.setState({ UserName })}
                underlineColorAndroid="transparent"
                style={styles.TextInput}
                />
                <TextInput
                placeholder="Enter Your Email"
                onChangeText={UserEmail => this.setState({ UserEmail })}
                underlineColorAndroid="transparent"
                style={styles.TextInput}
                />
                <TextInput
                placeholder="Enter Your Password"
                onChangeText={UserPassword => this.setState({ UserPassword })}
                underlineColorAndroid="transparent"
                style={styles.TextInput}
                />
                <TextInput
                placeholder="Enter Your City name"
                onChangeText={UserCity => this.setState({ UserCity })}
                underlineColorAndroid="transparent"
                style={styles.TextInput}
                />
                <TouchableOpacity disabled = { this.state.disabled } activeOpacity = { 0.8 } style = { styles.Btn } onPress = { this.saveData }>
                   <Text style = { styles.btnText }>Verify</Text>
                </TouchableOpacity>
                <Button title = 'Next'  
                    onPress={this.nextbutton}
                />
 
                {
                    (this.state.loading)
                    ?
                        (<ActivityIndicator size = "large" />)
                    :
                        null
                }

                
            </View>
        );
    }
}

【问题讨论】:

  • 这段代码在运行吗?请重新检查 mobilecheck.js 屏幕的按钮 onPress 功能不同

标签: javascript php mysql reactjs react-native


【解决方案1】:

mobilecheck.js 文件中的场景中,您可以根据 API 的响应在 saveData() 函数中添加导航。相同的逻辑适用于 verifycode.js 文件

试试这个

//mobilecheck.js
import React, { Component } from "react";
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  ActivityIndicator,
  Platform,
  Button
} from "react-native";

export default class MobileCheck extends React.Component {
  constructor() {
    super();
    this.state = {
      TextInput_mobile_number: "",
      mobile_number: "",
      loading: false,
      disabled: false
    };
  }

  //   sendDatafun = () => {
  //     this.props.navigation.navigate("VerifyCode", {
  //       mobile_number: this.state.mobile_number
  //     });
  //   };

  saveData = () => {
    this.setState({ loading: true, disabled: true }, () => {
      fetch("http://192.168.2.186/otplogin/mobile_checkapi.php", {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          mobile_number: this.state.mobile_number
        })
      })
        .then(response => response.json())
        .then(responseJson => {
          alert(responseJson);
          this.setState({ loading: false, disabled: false });
          //Accroding to your response you can handle events
          this.props.navigation.navigate("VerifyCode", {
            mobile_number: this.state.mobile_number
          });
        })
        .catch(error => {
          console.error(error);
          this.setState({ loading: false, disabled: false });
        });
    });
  };

  render() {
    const { navigate } = this.props.navigation;
    return (
      <View style={styles.container}>
        <TextInput
          underlineColorAndroid="transparent"
          placeholder="Please Enter Your Mobile Number"
          style={styles.textInput}
          onChangeText={text => this.setState({ mobile_number: text })}
          // onChangeText={data => this.setState({ TextInput_mobile_number: data })}
          keyboardType={"numeric"}
        />

        <TouchableOpacity
          disabled={this.state.disabled}
          activeOpacity={0.8}
          style={styles.Btn}
          onPress={this.saveData}
        >
          <Text style={styles.btnText}>Get Code</Text>
        </TouchableOpacity>
        {/* <Button title="Next" onPress={this.sendDatafun} /> */}

        {this.state.loading ? <ActivityIndicator size="large" /> : null}
      </View>
    );
  }
}
//verifycode.js
import React, { Component } from "react";
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  ActivityIndicator,
  Platform,
  Button
} from "react-native";

export default class VerifyCode extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      code: "",
      TextInput_mobile_number: "",
      mobile_number: "",

      // new code
      UserName: "",
      UserEmail: "",
      UserPassword: "",
      UserCity: "",

      loading: false,
      disabled: false
    };
  }
  //     nextbutton = () =>
  //   {
  //      this.props.navigation.navigate('SignUp');

  //   }

  saveData = () => {
    // new code
    const { UserName } = this.state;
    const { UserEmail } = this.state;
    const { UserPassword } = this.state;
    const { UserCity } = this.state;
    this.setState({ loading: true, disabled: true }, () => {
      fetch("http://192.168.2.186/otplogin/verify_codeapi.php", {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          code: this.state.code,
          mobile_number: this.props.navigation.state.params.mobile_number,

          //new code
          user_name: UserName,

          user_email: UserEmail,

          user_password: UserPassword,

          user_city: UserCity
        })
      })
        .then(response => response.json())
        .then(responseJson => {
          alert(responseJson);
          this.setState({ loading: false, disabled: false });
          this.props.navigation.navigate("SignUp");
        })
        .catch(error => {
          console.error(error);
          this.setState({ loading: false, disabled: false });
        });
    });
  };

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.textStyle}>
          We send verification code to :{" "}
          {this.props.navigation.state.params.mobile_number}
        </Text>
        <TextInput
          underlineColorAndroid="transparent"
          placeholder="Please Enter Your Verification Code"
          style={styles.textInput}
          onChangeText={text => this.setState({ code: text })}
          keyboardType={"numeric"}
        />
        <TextInput
          placeholder="Enter Your Full Name"
          onChangeText={UserName => this.setState({ UserName })}
          underlineColorAndroid="transparent"
          style={styles.TextInput}
        />
        <TextInput
          placeholder="Enter Your Email"
          onChangeText={UserEmail => this.setState({ UserEmail })}
          underlineColorAndroid="transparent"
          style={styles.TextInput}
        />
        <TextInput
          placeholder="Enter Your Password"
          onChangeText={UserPassword => this.setState({ UserPassword })}
          underlineColorAndroid="transparent"
          style={styles.TextInput}
        />
        <TextInput
          placeholder="Enter Your City name"
          onChangeText={UserCity => this.setState({ UserCity })}
          underlineColorAndroid="transparent"
          style={styles.TextInput}
        />
        <TouchableOpacity
          disabled={this.state.disabled}
          activeOpacity={0.8}
          style={styles.Btn}
          onPress={this.saveData}
        >
          <Text style={styles.btnText}>Verify</Text>
        </TouchableOpacity>
        {/* <Button title="Next" onPress={this.nextbutton} /> */}

        {this.state.loading ? <ActivityIndicator size="large" /> : null}
      </View>
    );
  }
}

或者,如果您想在一个按钮内添加两个功能,您可以这样做,

functionOne(){
// do something
}

functionTwo(){
// do someting
}

<TouchableOpacity onPress={() => { this.functionOne(); this.functionTwo(); }/> 

【讨论】:

    【解决方案2】:

    您可以使用单个 onPress 本身来实现此目的。如果database 响应成功,您可以通过两种方式转到下一页,

    1. 如果您想根据state 更新渲染多个屏幕,您可以将登录屏幕state 设置为false,然后设置所需的屏幕sstateastrue`,如下所示。假设您想要的屏幕是主屏幕,

      this.setState({ 
         loading: false, 
         disabled: false,
         loginScreen: false,  
         homeScreen: true    //This `state` update will render the home screen
      });
      

    那你的render()一定是这样的,

      render() {
          if(this.state.loginScreen) {
             //login screen content
          } else if(this.state.homeScreen) {
             //home screen content
          }
      }
    

    2.如果您正在使用任何路由包,那么您可以进入下一个屏幕,如下所示,

      this.props.history.push('/homeScreen'); 
    

    如果您使用 react-router-native,这只是一个示例。还有其他的包也一样。

    请记住,以上任何一种方式都必须在您的database 请求的响应中实现。

    如有任何疑问,请随时提出。

    【讨论】:

      猜你喜欢
      • 2017-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      • 2018-02-01
      • 2020-05-10
      • 2019-10-25
      相关资源
      最近更新 更多