當前位置: 首頁> 最新文章列表> 使用PHP 與React Native 構建高性能原生移動應用指南

使用PHP 與React Native 構建高性能原生移動應用指南

M66 2025-10-16

使用PHP 構建原生移動應用

雖然PHP 主要用於服務器端開發,但藉助React Native,開發者可以使用PHP 構建具有原生性能和界面的移動應用。通過PHP 提供API 服務,移動端可以實時更新數據,實現高效的交互體驗。

實戰案例:創建一個簡單計數器應用

創建React Native 項目

mkdir counter-app
cd counter-app
npx react-native init CounterApp --template react-native-template-typescript

在PHP 服務器中創建api.php 文件

<?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]);
}
?>

在App.tsx 中調用API

 // Import React and useState
import React, { useState } from &#39;react&#39;;

const App = () => {
  const [count, setCount] = useState(0);

  const handleIncrement = () => {
    fetch(&#39;http://localhost:3000/api.php&#39;, {
      method: &#39;POST&#39;,
      headers: {
        &#39;Content-Type&#39;: &#39;application/json&#39;,
      },
      body: JSON.stringify({ operation: &#39;increment&#39; }),
    })
      .then(res => res.json())
      .then(data => setCount(data.count))
      .catch(error => console.error(error));
  };

  const handleDecrement = () => {
    fetch(&#39;http://localhost:3000/api.php&#39;, {
      method: &#39;POST&#39;,
      headers: {
        &#39;Content-Type&#39;: &#39;application/json&#39;,
      },
      body: JSON.stringify({ operation: &#39;decrement&#39; }),
    })
      .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 開發到應用調用的全過程,非常適合希望快速上手原生移動開發的開發者。