PHP는 주로 서버 측 개발에 사용되지만 React Native를 사용하면 개발자는 PHP를 사용하여 기본 성능과 인터페이스를 갖춘 모바일 앱을 구축할 수 있습니다. PHP를 통해 API 서비스를 제공함으로써 모바일 단말기는 실시간으로 데이터를 업데이트하여 효율적인 대화형 경험을 얻을 수 있습니다.
mkdir 카운터 앱 CD 카운터 앱 npx 반응 네이티브 초기화 CounterApp --template 반응 네이티브 템플릿 유형 스크립트
<?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json"); $data = json_decode(file_get_contents("php://input")); if (isset($data-> 작업)) { 스위치 ($data->작업) { 사례 "증분": $count = (int) file_get_contents("count.txt") + 1; 부서지다; 사례 "감소": $count = (int) file_get_contents("count.txt") - 1; 부서지다; 기본: $count = (int) file_get_contents("count.txt"); 부서지다; } file_put_contents("count.txt", $count); echo json_encode(["count" => $count]); } ?>
// React 및 useState 가져오기 import React, 'react'에서 { useState }; const 앱 = () => { const [count, setCount] = useState(0); const handlerIncrement = () => { fetch('http://localhost:3000/api.php', { 메소드: 'POST', 헤더: { '콘텐츠 유형': '응용 프로그램/json', }, 본문: JSON.stringify({ 작업: 'increment' }), }) .then(res => res.json()) .then(데이터 => setCount(data.count)) .catch(오류 => console.error(오류)); }; const handlerDecrement = () => { fetch('http://localhost:3000/api.php', { 메소드: 'POST', 헤더: { '콘텐츠 유형': '응용 프로그램/json', }, 본문: JSON.stringify({ 작업: '감소' }), }) .then(res => res.json()) .then(데이터 => setCount(data.count)) .catch(오류 => console.error(오류)); }; 반품 ( <View style={styles.container}> <Text style={styles.title}>카운터 신청</Text> <Text style={styles.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> ); }; 기본 앱 내보내기;
npx 반응 네이티브 실행 iOS
앱을 실행한 후 버튼을 클릭하면 카운트를 늘리거나 줄일 수 있습니다. 브라우저를 통해 API 경로에 접속하면 요청 결과 및 데이터 변경 사항을 확인할 수 있습니다.
위는 React Native와 함께 PHP를 사용하여 네이티브 모바일 애플리케이션을 구축하는 완전한 실제 사례로, 프로젝트 생성, API 개발부터 애플리케이션 호출까지 전체 프로세스를 다루고 있습니다. 네이티브 모바일 개발을 빠르게 시작하려는 개발자에게 매우 적합합니다.