如何使用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
相关产品推荐
相关产品推荐

