虽然 PHP 主要用于服务器端开发,但借助 React Native,开发者可以使用 PHP 构建具有原生性能和界面的移动应用。通过 PHP 提供 API 服务,移动端可以实时更新数据,实现高效的交互体验。
mkdir counter-app cd counter-app npx react-native init CounterApp --template react-native-template-typescript
<?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json"); $data = json_decode(file_get_contents("php://input")); if (isset($data->operation)) { switch ($data->operation) { case "increment": $count = (int) file_get_contents("count.txt") + 1; break; case "decrement": $count = (int) file_get_contents("count.txt") - 1; break; default: $count = (int) file_get_contents("count.txt"); break; } file_put_contents("count.txt", $count); echo json_encode(["count" => $count]); } ?>
// Import React and useState import React, { useState } from 'react'; const App = () => { const [count, setCount] = useState(0); const handleIncrement = () => { fetch('http://localhost:3000/api.php', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ operation: 'increment' }), }) .then(res => res.json()) .then(data => setCount(data.count)) .catch(error => console.error(error)); }; const handleDecrement = () => { fetch('http://localhost:3000/api.php', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ operation: 'decrement' }), }) .then(res => res.json()) .then(data => setCount(data.count)) .catch(error => console.error(error)); }; return ( <View style={styles.container}> <Text style={styles.title}>Counter Application</Text> <Text style={styles.count}>{count}</Text> <TouchableOpacity style={styles.button} onPress={handleIncrement}> <Text style={styles.buttonText}>+</Text> </TouchableOpacity> <TouchableOpacity style={styles.button} onPress={handleDecrement}> <Text style={styles.buttonText}>-</Text> </TouchableOpacity> </View> ); }; export default App;
npx react-native run-ios
启动应用后,点击按钮可以增加或减少计数。通过浏览器访问 API 路径,可以查看请求结果和数据变化。
以上就是使用 PHP 配合 React Native 构建原生移动应用的完整实战案例,涵盖项目创建、API 开发到应用调用的全过程,非常适合希望快速上手原生移动开发的开发者。