当前位置: 首页> 最新文章列表> 使用 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 '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 开发到应用调用的全过程,非常适合希望快速上手原生移动开发的开发者。