Moment For Technology

Taro supports rich text (wechat applet)

Posted on May 26, 2023, 11:19 a.m. by Tina Howard
Category: The front end Tag: The front end taro

Requirements: Let's talk about the requirements first, that is, we need to make the active page. The active page has a rule, and the content of the rule is configured by the BACKGROUND of the B end. The page is as follows

Implementation: need to use dangerouslySetInnerHTML attribute

Compared with other schemes, this attribute has the following advantages: 1. It supports the modification of rich text style. 2

Core code: index.tsx

  // Change the default styles in the image line
  (Taro as any).options.html.transformElement = (el) =  {
    if (el.nodeName === 'image') {
      el.setAttribute('mode'.'widthFix');
    }
    return el;
  };
  
  return (
    View className='content'
      View className='text' dangerouslySetInnerHTML={{ __html: rule}} / 
    /View
  );
Copy the code

If you also want to upload images, be sure to change mode, as it defaults to mode="scaleToFill", which will cause scaling and not achieve the desired effect. So the following code must be added. All the code is at the end

  // Change the default styles in the image line
  (Taro as any).options.html.transformElement = (el) =  {
    if (el.nodeName === 'image') {
      el.setAttribute('mode'.'widthFix');
    }
    return el;
  };
Copy the code

Here are the results:

Complete code:

index.ts

import { getUser, IglobalUser } from '@/utils/getUser';

import { View } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import { useEffect, useState } from 'react';
import { getActivityRule } from '@/services/activity.service';
import './index.scss';

const Rule = () =  {
  const router = useRouter();
  const activityCode: string = router.params.activity_code || ' ';
  const [rule, setRule] = useState(' ');
  // Get the rule
  const getRule = async() =  {try {
      const globalUser: IglobalUser = await getUser();
      const { userId } = globalUser;
      const res = await getActivityRule({ activityCode, userId });
      if (res.status === 0) { setRule(res.result); }}catch (error) {}
  };
  useEffect(() = { getRule(); } []);// Change the default styles in the image line
  (Taro as any).options.html.transformElement = (el) =  {
    if (el.nodeName === 'image') {
      el.setAttribute('mode'.'widthFix');
    }
    return el;
  };

  return (
    View className='content'
      View className='text' dangerouslySetInnerHTML={{ __html: rule}} / 
    /View
  );
};
export default Rule;
Copy the code

index.scss

.content {
  .text {
    .h5-p {
      .h5-img {
        width: 100%;
        overflow: scroll;
        display: block; }}}}Copy the code

Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.