【问题标题】:How to grab a <span> with a particular class using react-native-render-html如何使用 react-native-render-html 获取具有特定类的 <span>
【发布时间】:2021-10-19 03:43:22
【问题描述】:

我有一个特定的&lt;span&gt; 需要自定义渲染

<p><span class="ql-formula" data-value="(x^2 + 4)(x^2 - 4)"></span></p>

因此,如果我的 span 标签具有类 ql-formula,我想使用 this 库中的 MathText 来渲染它,否则 span 标签应该默认渲染。我如何使用this 库获取特定的跨度标签。例如,this 库可以通过以下方式实现类似的行为,

const renderNode = (node, index) => {
  if (
    node.name == 'span' &&
    node.attribs.class == 'ql-formula' &&
    node.attribs['data-value']
  ) {
    return (
      <MathText
        key={index}
        value={`$$${node.attribs['data-value']}$$`}
        direction="ltr"
        CellRenderComponent={props => <MathView {...props} />}
      />
    );
  }
};



<HTMLView value={htmlContent} renderNode={renderNode} />

但我不能使用这个库,因为它有一些其他限制

【问题讨论】:

    标签: javascript html react-native react-native-render-html


    【解决方案1】:

    经过大量的研发,我能够弄清楚。这是我的做法。

    const renderers = {
      span: ({TDefaultRenderer, tnode, ...props}) => {
        const a = tnode.domNode.attribs;
        if (a.class == 'ql-formula') {
          return (
            <MathText
              key={Math.random()}
              value={`$$${a['data-value']}$$`}
              direction="ltr"
              CellRenderComponent={prop => <MathView {...prop} />}
            />
          );
        }
        return <TDefaultRenderer tnode={tnode} {...props} />;
      },
    };
    
    const App = () => {
      const {width} = useWindowDimensions();
      return (
        <View style={{flex: 1, backgroundColor: '#fcc', marginTop: 50}}>
          <RenderHtml contentWidth={width} source={source} renderers={renderers} />
        </View>
      );
    };
    

    【讨论】:

    • 你明白了!更简单:if (tnode.hasClass('ql-formula')) { return &lt;MathText .../&gt; } return &lt;TDefault... /&gt;
    猜你喜欢
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多