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

如何使用react-native-render-html获取指定class的span标签渲染数学公式

实现步骤

react-native-render-html 通过自定义标签渲染器即可实现需求,具体实现如下:

1. 导入依赖

import RenderHTML from 'react-native-render-html';
import { MathText, MathView } from 'react-native-math-view';
import { useWindowDimensions } from 'react-native';

2. 定义自定义渲染器配置

const renderers = {
  span: ({ InternalRenderer, tnode, key, style }) => {
    const attribs = tnode.attributes;
    // 匹配指定class的公式标签
    if (attribs.class === 'ql-formula' && attribs['data-value']) {
      return (
        <MathText
          key={key}
          value={`$$${attribs['data-value']}$$`}
          direction="ltr"
          CellRenderComponent={props => <MathView {...props} />}
        />
      );
    }
    // 其余span走默认渲染逻辑
    return <InternalRenderer key={key} tnode={tnode} style={style} />;
  }
};

3. 组件中调用

const YourComponent = () => {
  // contentWidth为必填属性,用于自适应布局
  const { width } = useWindowDimensions();
  // 你的HTML内容
  const htmlContent = `<p><span class="ql-formula" data-value="(x^2 + 4)(x^2 - 4)"></span></p>`;
  
  return (
    <RenderHTML
      contentWidth={width}
      source={{ html: htmlContent }}
      renderers={renderers}
    />
  );
};

注意说明

  • tnode.attributes 存储了当前标签的所有属性,用法和react-native-htmlview的node.attribs一致
  • InternalRenderer是框架提供的内置默认渲染器,不需要自定义的场景直接返回即可保留原有渲染逻辑

内容的提问来源于stack exchange,提问作者sumesh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 04:30:01