React Native Render HTML自定义渲染:如何设置tnode子文本节点样式?
解决React Native Render HTML特定#text节点的条件样式问题
要给特定项的#text子节点同时设置删除线和文本颜色,且支持条件样式、不能用defaultTextProps,可以试试下面两种方案:
方法一:自定义目标标签渲染器,修改子文本节点样式
针对你要处理的特定HTML标签(比如<del>),自定义它的渲染函数,遍历子节点筛选出所有#text类型的节点,直接修改其样式属性:
import { RenderHTMLProps, TChildrenRenderer, TNode } from 'react-native-render-html'; const customRenderers: RenderHTMLProps['customRenderers'] = { // 替换为你要处理的目标标签,比如del、s或自定义标签 del: (props) => { const { tnode, ...restProps } = props; const styledChildren = tnode.children.map((childNode) => { if (childNode.type === '#text') { // 这里替换成你的条件判断逻辑,比如根据父节点属性、文本内容等 const shouldApplyStyle = true; if (shouldApplyStyle) { return { ...childNode, styles: { ...childNode.styles, color: 'red', textDecorationLine: 'line-through', }, }; } } return childNode; }); return <TChildrenRenderer tchildren={styledChildren} {...restProps} />; }, }; // 在RenderHTML组件中使用自定义渲染器 <RenderHTML source={{ html: '<del>需要修改样式的文本</del>' }} customRenderers={customRenderers} />
方法二:用transformTnode全局转换文本节点样式
通过transformTnode函数拦截所有节点,判断当前是否是目标#text节点(比如父节点为特定标签),再按需修改样式:
import { TNode } from 'react-native-render-html'; const transformTnode = (tnode: TNode) => { // 判断当前是#text节点,且父节点是你要处理的特定标签 if (tnode.type === '#text' && tnode.parent?.type === 'del') { // 添加你的条件判断逻辑 const meetsCondition = true; if (meetsCondition) { return { ...tnode, styles: { ...tnode.styles, color: 'red', textDecorationLine: 'line-through', }, }; } } return tnode; }; // 在RenderHTML中配置transformTnode <RenderHTML source={{ html: '<del>需要修改样式的文本</del>' }} transformTnode={transformTnode} />
为什么直接包裹TChildrenRenderer颜色不生效?
React Native的Text组件样式继承有局限性:textDecorationLine这类装饰样式可以继承,但color如果内部Text节点有自带样式(比如HTML默认样式、组件内置样式),会直接覆盖父级Text的color设置。而直接修改#text节点的styles属性,会让渲染时把样式直接应用到对应的Text组件上,就不会被覆盖了。
内容的提问来源于stack exchange,提问作者Slbox
相关产品推荐
相关产品推荐

