You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Expo CLI的React Native应用预约后短信通知实现咨询

实现Expo React Native预约后短信通知的方案

一、前端完成预约流程的逻辑实现

先在React Native组件里处理产品选中、时段选择的状态管理和提交逻辑:

  1. 用useState管理选中的产品、时段以及用户手机号(可让用户输入或从登录信息中获取):
import { useState } from 'react';
import { View, Button, TextInput, Picker, Alert } from 'react-native';

export default function BookingScreen() {
  const [selectedProduct, setSelectedProduct] = useState('');
  const [selectedTimeSlot, setSelectedTimeSlot] = useState('');
  const [userPhone, setUserPhone] = useState('');

  // 提交预约的处理函数
  const handleBookingSubmit = async () => {
    if (!selectedProduct || !selectedTimeSlot || !userPhone) {
      Alert.alert('提示', '请完善所有信息');
      return;
    }

    // 调用短信发送接口
    try {
      const response = await fetch('你的后端接口地址', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          phone: userPhone,
          timeSlot: selectedTimeSlot,
          product: selectedProduct
        })
      });

      if (response.ok) {
        Alert.alert('成功', '预约已提交,短信通知已发送');
        // 重置表单或跳转页面
        setSelectedProduct('');
        setSelectedTimeSlot('');
      } else {
        Alert.alert('失败', '预约提交失败,请重试');
      }
    } catch (error) {
      Alert.alert('异常', '网络连接失败,请稍后再试');
    }
  };

  return (
    <View style={{ padding: 20 }}>
      {/* 产品选择组件 */}
      <Picker
        selectedValue={selectedProduct}
        onValueChange={(itemValue) => setSelectedProduct(itemValue)}
        style={{ height: 50, width: '100%', marginBottom: 15 }}
      >
        <Picker.Item label="请选择产品" value="" />
        <Picker.Item label="产品A" value="productA" />
        <Picker.Item label="产品B" value="productB" />
      </Picker>

      {/* 时段输入框(也可替换为时间选择器组件) */}
      <TextInput
        placeholder="输入预约时段(如14:00-16:00)"
        value={selectedTimeSlot}
        onChangeText={setSelectedTimeSlot}
        style={{ borderWidth: 1, borderColor: '#ccc', padding: 10, marginBottom: 15, borderRadius: 5 }}
      />

      {/* 用户手机号输入 */}
      <TextInput
        placeholder="请输入接收短信的手机号"
        value={userPhone}
        onChangeText={setUserPhone}
        keyboardType="phone-pad"
        style={{ borderWidth: 1, borderColor: '#ccc', padding: 10, marginBottom: 20, borderRadius: 5 }}
      />

      <Button title="确认预约" onPress={handleBookingSubmit} />
    </View>
  );
}

二、短信发送的核心实现(依赖后端/第三方服务)

前端无法直接自动发送短信,必须通过后端调用第三方短信服务商API实现:

  1. 选择短信服务商:比如Twilio、阿里云短信、腾讯云短信等,注册账号后获取API密钥、申请短信模板(模板内容为Your Product is Booked at {time} time slot)。

  2. 搭建后端接口(以Node.js + Express为例):

const express = require('express');
const twilio = require('twilio'); // 以Twilio为例,其他服务商SDK逻辑类似
const app = express();
app.use(express.json());

// 替换为你的Twilio账号信息
const accountSid = '你的Twilio账号SID';
const authToken = '你的Twilio认证Token';
const client = twilio(accountSid, authToken);

app.post('/send-booking-sms', async (req, res) => {
  const { phone, timeSlot } = req.body;
  const messageContent = `Your Product is Booked at ${timeSlot} time slot`;

  try {
    await client.messages.create({
      body: messageContent,
      from: '你的Twilio分配手机号',
      to: phone // 注意格式:国内手机号需加+86,如+8613xxxxxxxxx
    });
    res.status(200).json({ success: true });
  } catch (error) {
    console.error('短信发送失败:', error);
    res.status(500).json({ success: false, msg: '短信发送失败' });
  }
});

app.listen(3000, () => console.log('后端服务启动在3000端口'));
  1. 注意事项:
    • 国内手机号建议使用国内短信服务商,需完成实名认证和模板审核,避免短信被拦截。
    • 后端接口需部署到公网环境,前端才能正常调用;也可以用Serverless函数(如Vercel Functions、AWS Lambda)替代完整后端,逻辑和上述接口一致。

三、备选方案:调用用户本地短信应用(非自动发送)

如果不需要自动发送,仅触发用户手动发送短信,可使用Expo的expo-sms库:

  1. 安装依赖:
npx expo install expo-sms
  1. 在组件中修改提交逻辑:
import * as SMS from 'expo-sms';

// 修改handleBookingSubmit函数
const handleBookingSubmit = async () => {
  if (!selectedProduct || !selectedTimeSlot || !userPhone) {
    Alert.alert('提示', '请完善所有信息');
    return;
  }

  const messageContent = `Your Product is Booked at ${selectedTimeSlot} time slot`;
  const isAvailable = await SMS.isAvailableAsync();
  
  if (isAvailable) {
    await SMS.sendSMSAsync([userPhone], messageContent);
  } else {
    Alert.alert('提示', '当前设备不支持短信功能');
  }
};

内容的提问来源于stack exchange,提问作者MayukhAcharya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 13:55:56