React Native中结合Axios使用JSON及WordPress内容拆分展示问题
Hey there! Let's break down your two React Native questions with practical, actionable steps:
Axios is a go-to tool for handling HTTP requests, and it works seamlessly with JSON in React Native. Here's how to use them together:
First, install Axios
Open your terminal and run this in your project root:npm install axios # Or use yarn if you prefer yarn add axiosFetch JSON data with a GET request
Let's say you want to pull JSON data from an API. Here's a quick example:import axios from 'axios'; import { useEffect, useState } from 'react'; import { View, Text } from 'react-native'; const JsonFetcher = () => { const [data, setData] = useState(null); const [error, setError] = useState(null); const fetchData = async () => { try { // Replace with your actual API URL const response = await axios.get('https://your-api-endpoint.com/data'); // The JSON payload lives in response.data setData(response.data); } catch (err) { setError(err.message); } }; useEffect(() => { fetchData(); }, []); if (error) return <Text>Error: {error}</Text>; if (!data) return <Text>Loading...</Text>; return ( <View> <Text>Fetched JSON Title: {data.title}</Text> <Text>Fetched JSON Content: {data.content}</Text> </View> ); }; export default JsonFetcher;Send JSON data with a POST request
When submitting JSON to a server, Axios automatically sets theContent-Typeheader toapplication/jsonfor you, but you can explicitly define it if needed:const submitJsonData = async () => { try { const payload = { username: 'react-native-user', message: 'Hello from Axios!' }; const response = await axios.post('https://your-api-endpoint.com/submit', payload); console.log('Submission successful:', response.data); } catch (err) { console.error('Submission failed:', err.message); } };
WordPress returns post content as HTML (from its editor), so we need to parse that HTML to split out text, images, and other elements, then render them with React Native components.
Recommended approach: Use an HTML parsing library
Regex is unreliable for HTML parsing, so we'll use cheerio—a lightweight, jQuery-like library for parsing HTML:
Install cheerio
npm install cheerio # Or yarn yarn add cheerioParse content and render elements
This example will split the HTML into text blocks and images, then render each with appropriate React Native components:import cheerio from 'cheerio'; import { View, Text, Image, StyleSheet } from 'react-native'; const PostContentRenderer = ({ contentHtml }) => { const $ = cheerio.load(contentHtml); const contentElements = []; // Traverse top-level elements in the content $('body > *').each((index, element) => { const tag = element.tagName.toLowerCase(); // Handle images if (tag === 'img') { const imageSrc = $(element).attr('src'); contentElements.push({ type: 'image', src: imageSrc, alt: $(element).attr('alt') || 'Post image' }); } // Handle text elements (paragraphs, headings, etc.) else { const textContent = $(element).text().trim(); if (textContent) { contentElements.push({ type: 'text', content: textContent, tag: tag // Track original tag to style differently }); } } }); // Render each element with matching React Native components return ( <View style={styles.container}> {contentElements.map((item, idx) => { if (item.type === 'image') { return ( <Image key={idx} source={{ uri: item.src }} style={styles.image} resizeMode="contain" accessibilityLabel={item.alt} /> ); } else { // Apply different styles based on original HTML tag const textStyle = item.tag.startsWith('h') ? styles.heading : styles.paragraph; return ( <Text key={idx} style={textStyle}> {item.content} </Text> ); } })} </View> ); }; const styles = StyleSheet.create({ container: { gap: 16, paddingHorizontal: 16, paddingVertical: 8 }, image: { width: '100%', height: 220, borderRadius: 8 }, heading: { fontSize: 20, fontWeight: '600', marginVertical: 4 }, paragraph: { fontSize: 16, lineHeight: 24, color: '#333' } }); export default PostContentRenderer;
Quick note
WordPress REST API returns the rendered content in the content.rendered field—pass that directly to the PostContentRenderer component's contentHtml prop.
内容的提问来源于stack exchange,提问作者edris satiyari

