所以我有以下格式的html字符串:
Our society reflects, and is a reflection of, the <del>individual</del><add>person</add> (you and I) , and the <del>individual</del><add>person</add> is a <del>reflection</del><add>manifestation</add> of society (hologram/holon ).
我想将它们解析为打击之类的节点:
Our society reflects, and is a reflection of, the
<del>individual</del>
<add>person</add>
(you and I) , and the
<del>individual</del>
<add>person</add>
is a
<del>reflection</del>
<add>manifestation</add>
of society (hologram/holon ).
我知道您可以做类似的事情:
var element = document.createElement( 'html' );
element.innerHTML = html
nodes = element.childNodes
但是在react native中,我得到了can't find variable: document
,看来我需要web-view
来做到这一点。有没有其他方法可以解析此字符串?
答案 0 :(得分:1)
如果文本中没有嵌套节点,也没有<
>
,那么一种快速而又肮脏的解决方案将是match
子字符串,这些子字符串要么以标签开始,以该标签,或不包含任何标签:
const str = `Our society reflects, and is a reflection of, the <del>individual</del><add>person</add> (you and I) , and the <del>individual</del><add>person</add> is a <del>reflection</del><add>manifestation</add> of society (hologram/holon ).`;
console.log(str.match(/<(\w+)>[^\<]+<\/\1>|[^<>]+/g))
如果要在子字符串的开头和结尾处修剪空格,则也要在其中匹配非空格:
const str = `Our society reflects, and is a reflection of, the <del>individual</del><add>person</add> (you and I) , and the <del>individual</del><add>person</add> is a <del>reflection</del><add>manifestation</add> of society (hologram/holon ).`;
console.log(str.match(/<(\w+)>[^\<]+<\/\1>|[^<>\s][^<>]+[^<>\s]/g))
但是找到一个真正的XML解析器将是更好的常规选择。
答案 1 :(得分:1)
您在这里有几个选择,就像您提到的那样,您可以像这样使用WebView:
<WebView source={{html:"your_html_string"}} />
您还可以使用像这样的npm软件包:
https://github.com/archriss/react-native-render-html
或者您可以自己解析该字符串,然后使用<Text />
元素将其转换为JSX标记
import { Text } from 'react-native';
import React, { Component } from 'react';
class del extends Text {
render() {
return (
<Text style={{textDecoration:'line-through'}} ...this.props>{super.render()}</Text>
)
}
}
class add extends Text {
render() {
return (
<Text style={{textDecoration:'underline line-through'}} ...this.props>{super.render()}</Text>
)
}
}
export default MyScreen extends Component {
render() {
return (
<Text>"Our society reflects, and is a reflection of, the"
<del>"individual"</del>
<add>"person"</add>
"(you and I) , and the"
<del>"individual"</del>
<add>"person"</add>
"is a "
<del>"reflection"</del>
<add>"manifestation"</add>
"of society (hologram/holon )."
</Text>
)
}
}
答案 2 :(得分:0)
https://github.com/meliorence/react-native-render-html
来自文档:
import React from 'react';
import { useWindowDimensions } from 'react-native';
import RenderHtml from 'react-native-render-html';
const source = {
html: `
<p style='text-align:center;'>
Hello World!
</p>`
};
export default function App() {
const { width } = useWindowDimensions();
return (
<RenderHtml
contentWidth={width}
source={source}
/>
);
}