React Native 快速开始
- AI 快速开始
- 完整开发指引
准备工作
在开始之前,请确保您已完成以下准备:
- 开通云开发环境:开通云开发环境
- 获取 API 访问凭证:在 CloudBase 控制台 获取环境 ID 和 API 密钥
Client
配置你的 AI 工具以连接 CloudBase 能力 支持本地与托管两种连接方式,详见 连接方式。
步骤 1:安装 / 配置 CloudBase
步骤 2:和 AI 对话
在 AI 对话中依次输入以下内容:
prompt
安装 CloudBase Skills:命令 npx skills add tencentcloudbase/cloudbase-skills -y使用 CloudBase Skills: 使用 CloudBase Skills:在 React Native 应用中集成 CloudBase HTTP API准备工作
在开始之前,请确保您已完成以下准备:
- 开通云开发环境:开通云开发环境
- 获取 API 访问凭证:在 CloudBase 控制台 获取环境 ID 和 API 密钥
更多详情请参考:React Native 完整文档
安装 SDK
@cloudbase/js-sdk 配合 @cloudbase/adapter-rn 可以让您在 React Native 项目中使用 JavaScript 访问 CloudBase 服务 和资源。
npm
npm i @cloudbase/js-sdk @cloudbase/adapter-rn
yarn
yarn add @cloudbase/js-sdk @cloudbase/adapter-rn
pnpm
pnpm add @cloudbase/js-sdk @cloudbase/adapter-rn
iOS 需 要安装原生依赖:
cd ios && pod install && cd ..
初始化 SDK
新增如下代码到您的 React Native 项目
src/utils/cloudbase.js
import cloudbaseSDK from "@cloudbase/js-sdk";
import adapter from "@cloudbase/adapter-rn";
cloudbaseSDK.useAdapters(adapter);
const cloudbase = cloudbaseSDK.init({
// 环境 ID
env: "{%ENV_ID%}",
// 地域
region: "{%REGION%}",
// 匿名访问令牌
accessKey: "{%PUBLISHABLE_KEY%}"
});
export default cloudbase;
身份认证
- 短信验证码注册
- 邮箱验证码注册
- 账号密码登录
- 短信验证码登录
- 邮箱验证码登录
- 匿名登录
使用 短信验证码注册 请先前往 身份认证/登录方式 开启 短信验证码
调用方式:
import cloudbase from "./utils/cloudbase";
const auth = cloudbase.auth();
// 发送验证码
const res = await auth.getVerification({ phone_number: phone });
// 验证验证码
const verifyRes = await auth.verify({
verification_id: verificationId,
verification_code: code
});
// 注册(如用户已存在则自动登录)
await auth.signUp({
phone_number: `+86 ${phone}`,
verification_code: code,
verification_token: verifyRes.verification_token,
name: `user_${phone.slice(-4)}`,
password: "admin@123"
});
完整示例:
import React, { useState } from "react";
import { View, Text, TextInput, Button, StyleSheet, Alert } from "react-native";
import cloudbase from "./utils/cloudbase";
export default function SmsRegister() {
const [phone, setPhone] = useState("");
const [code, setCode] = useState("");
const [verificationId, setVerificationId] = useState("");
const [message, setMessage] = useState("");
// 发送验证码
const sendCode = async () => {
try {
const auth = cloudbase.auth();
const res = await auth.getVerification({ phone_number: phone });
setVerificationId(res.verification_id);
setMessage("验证码已发送!");
} catch (error) {
setMessage(`发送失败: ${error.message}`);
}
};
// 注册
const register = async () => {
try {
const auth = cloudbase.auth();
// 验证验证码
const verifyRes = await auth.verify({
verification_id: verificationId,
verification_code: code
});
// 注册(如用户已存在则自动登录)
await auth.signUp({
phone_number: `+86 ${phone}`,
verification_code: code,
verification_token: verifyRes.verification_token,
name: `user_${phone.slice(-4)}`,
password: "admin@123"
});
setMessage("注册成功!");
Alert.alert("成功", "注册成功");
} catch (error) {
setMessage(`注册失败: ${error.message}`);
Alert.alert("失败", `注册失败: ${error.message}`);
}
};
return (
<View style={styles.container}>
<Text>手机号:</Text>
<TextInput
style={styles.input}
value={phone}
onChangeText={setPhone}
placeholder="13800000000"
keyboardType="phone-pad"
/>
<Text>验证码:</Text>
<View style={styles.row}>
<TextInput
style={[styles.input, styles.codeInput]}
value={code}
onChangeText={setCode}
placeholder="验证码"
keyboardType="numeric"
/>
<Button title="发送验证码" onPress={sendCode} disabled={!phone} />
</View>
<Button
title="注册"
onPress={register}
disabled={!verificationId || !code}
/>
{message && (
<Text
style={[
styles.message,
{ color: message.includes("成功") ? "green" : "red" }
]}
>
{message}
</Text>
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20
},
input: {
height: 40,
borderColor: "#ccc",
borderWidth: 1,
marginVertical: 10,
paddingHorizontal: 10,
borderRadius: 5
},
row: {
flexDirection: "row",
alignItems: "center"
},
codeInput: {
flex: 1,
marginRight: 10
},
message: {
marginTop: 20,
textAlign: "center"
}
});
使用 邮箱验证码注册 请先前往 身份认证/登录方式 开启 邮箱验证码
调用方式:
import cloudbase from "./utils/cloudbase";
const auth = cloudbase.auth();
// 发送验证码
const res = await auth.getVerification({ email });
// 验证验证码
const verifyRes = await auth.verify({
verification_id: verificationId,
verification_code: code
});
// 注册(如用户已存在则自动登录)
await auth.signUp({
email,
verification_code: code,
verification_token: verifyRes.verification_token,
name: `user_${email.slice(-4)}`,
password: "admin@123"
});
完整示例:
import React, { useState } from "react";
import { View, Text, TextInput, Button, StyleSheet, Alert } from "react-native";
import cloudbase from "./utils/cloudbase";
export default function EmailRegister() {
const [email, setEmail] = useState("");
const [code, setCode] = useState("");
const [verificationId, setVerificationId] = useState("");
const [message, setMessage] = useState("");
// 发送验证码
const sendCode = async () => {
try {
const auth = cloudbase.auth();
const res = await auth.getVerification({ email });
setVerificationId(res.verification_id);
setMessage("验证码已发送!");
} catch (error) {
setMessage(`发送失败: ${error.message}`);
}
};
// 注册
const register = async () => {
try {
const auth = cloudbase.auth();
// 验证验证码
const verifyRes = await auth.verify({
verification_id: verificationId,
verification_code: code
});
// 注册(如用户已存在则自动登录)
await auth.signUp({
email,
verification_code: code,
verification_token: verifyRes.verification_token,
name: `user_${email.slice(-4)}`,
password: "admin@123"
});
setMessage("注册成功!");
Alert.alert("成功", "注册成功");
} catch (error) {
setMessage(`注册失败: ${error.message}`);
Alert.alert("失败", `注册失败: ${error.message}`);
}
};
return (
<View style={styles.container}>
<Text>邮箱:</Text>
<TextInput
style={styles.input}
value={email}
onChangeText={setEmail}
placeholder="example@email.com"
keyboardType="email-address"
/>
<Text>验证码:</Text>
<View style={styles.row}>
<TextInput
style={[styles.input, styles.codeInput]}
value={code}
onChangeText={setCode}
placeholder="验证码"
keyboardType="numeric"
/>
<Button title="发送验证码" onPress={sendCode} disabled={!email} />
</View>
<Button
title="注册"
onPress={register}
disabled={!verificationId || !code}
/>
{message && (
<Text
style={[
styles.message,
{ color: message.includes("成功") ? "green" : "red" }
]}
>
{message}
</Text>
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20
},
input: {
height: 40,
borderColor: "#ccc",
borderWidth: 1,
marginVertical: 10,
paddingHorizontal: 10,
borderRadius: 5
},
row: {
flexDirection: "row",
alignItems: "center"
},
codeInput: {
flex: 1,
marginRight: 10
},
message: {
marginTop: 20,
textAlign: "center"
}
});
使用 账号密码登录 请先前往 身份认证/登录方式 开启 用户名密码登录
调用方式:
import cloudbase from "./utils/cloudbase";
const auth = cloudbase.auth();
await auth.signIn({
username, // 可以是用户名、手机号或邮箱
password
});
完整示例:
import React, { useState } from "react";
import { View, Text, TextInput, Button, StyleSheet, Alert } from "react-native";
import cloudbase from "./utils/cloudbase";
export default function PasswordLogin() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [message, setMessage] = useState("");
// 登录
const login = async () => {
try {
const auth = cloudbase.auth();
await auth.signIn({
username, // 可以是用户名、手机号或邮箱
password
});
setMessage("登录成功!");
Alert.alert("成功", "登录成功");
} catch (error) {
setMessage(`登录失 败: ${error.message}`);
Alert.alert("失败", `登录失败: ${error.message}`);
}
};
return (
<View style={styles.container}>
<Text>账号:</Text>
<TextInput
style={styles.input}
value={username}
onChangeText={setUsername}
placeholder="用户名/手机号/邮箱"
/>
<Text style={styles.note}>注:手机号登录请添加区号 +86</Text>
<Text>密码:</Text>
<TextInput
style={styles.input}
value={password}
onChangeText={setPassword}
placeholder="请输入密码"
secureTextEntry
/>
<Button title="登录" onPress={login} disabled={!username || !password} />
{message && (
<Text
style={[
styles.message,
{ color: message.includes("成功") ? "green" : "red" }
]}
>
{message}
</Text>
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20
},
input: {
height: 40,
borderColor: "#ccc",
borderWidth: 1,
marginVertical: 10,
paddingHorizontal: 10,
borderRadius: 5
},
note: {
fontSize: 12,
color: "#666",
marginBottom: 10
},
message: {
marginTop: 20,
textAlign: "center"
}
});
使用 短信验证码登录 请先前往 身份认证/登录方式 开启 短信验证码登录