需求:先说下需求,就是我们需要做活动页面,活动页面有个规则,规则的内容由B端后台配置海报页。页面如下
实现:
需要用到dangerouslySetInnerHTML属性即可,这个属性相比于其他方案的优势在于:1. 支持修改富文本样式 2. Taro官方属性,比插件靠谱
核心代码:index.tsx
// 修改图片行内默认样式
(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>
);
如果你的需求也是传图片,记得一定要修改mode,因为它默认是mode="scaleToFill", 这会导致缩放,不能达到预期效果。所以下面代码一定要加。文末有所有代码
// 修改图片行内默认样式
(Taro as any).options.html.transformElement = (el) => {
if (el.nodeName === 'image') {
el.setAttribute('mode', 'widthFix');
}
return el;
};
来看成果:
完整代码:
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('');
// 获取规则
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();
}, []);
// 修改图片行内默认样式
(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;
index.scss
.content {
.text {
.h5-p {
.h5-img {
width: 100%;
overflow: scroll;
display: block;
}
}
}
}