以下是一个简单的示例代码,演示如何使用React Native编写一个钱包转账页面:

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

const TransferPage = () => {
  const [amount, setAmount] = useState('');
  const [recipient, setRecipient] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleTransfer = async () => {
    setError('');
    setLoading(true);

    // 进行转账逻辑
    try {
      // 发送转账请求,根据你的具体业务逻辑实现
      const response = await fetch('https://your-api-url/transfer', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ amount, recipient }),
      });

      if (response.ok) {
        // 转账成功
        console.log('Transfer success!');
      } else {
        // 转账失败
        console.log('Transfer failed!');
        setError('Transfer failed');
      }
    } catch (error) {
      console.error(error);
      setError('An error occurred');
    }

    setLoading(false);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.errorText}>{error}</Text>
      <TextInput
        style={styles.input}
        placeholder="Recipient"
        value={recipient}
        onChangeText={setRecipient}
      />
      <TextInput
        style={styles.input}
        placeholder="Amount"
        value={amount}
        onChangeText={setAmount}
        keyboardType="numeric"
      />
      <Button
        title={loading ? 'Loading...' : 'Transfer'}
        onPress={handleTransfer}
        disabled={loading}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  input: {
    width: '100%',
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    marginBottom: 10,
    paddingLeft: 10,
  },
  errorText: {
    color: 'red',
    marginBottom: 10,
  },
});

export default TransferPage;

在上述代码中,我们使用了React Hooks来管理组件的状态。amountrecipient分别用于存储转账金额和收款人信息。loading用于控制转账按钮的加载状态,error用于显示错误信息。

handleTransfer函数表示点击转账按钮时的事件处理函数。在该函数中,我们首先清除之前的错误信息,然后将loading设置为true来显示加载状态。接下来,我们使用fetch方法发送转账请求,根据响应的状态码来判断转账是否成功,并相应地更新状态。最后,将loading设置为false来隐藏加载状态。

在页面渲染部分,我们使用ViewTextInputButton等组件来构建页面的视图结构。TextInput用于输入收款人和转账金额,Button用于触发转账事件。同时,我们使用了StyleSheet来定义样式。

请根据你的具体业务需求和样式风格进行相应的修改和调整


原文地址: http://www.cveoy.top/t/topic/ieQ4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录