You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中结合Axios使用JSON及WordPress内容拆分展示问题

Hey there! Let's break down your two React Native questions with practical, actionable steps:

1. 如何在React Native中结合Axios使用JSON?

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 axios
    
  • Fetch 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 the Content-Type header to application/json for 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);
      }
    };
    
2. 拆分WordPress Post的content字段并以标签形式展示

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.

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 cheerio
    
  • Parse 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:44:16