雖然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 開發到應用調用的全過程,非常適合希望快速上手原生移動開發的開發者。