forked from jsdf/react-native-htmlview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTMLView.js
More file actions
91 lines (78 loc) · 1.95 KB
/
HTMLView.js
File metadata and controls
91 lines (78 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import React, { Component } from "react";
import htmlToElement from "./htmlToElement";
import { Linking, StyleSheet, Text } from "react-native";
const boldStyle = { fontWeight: "500" };
const italicStyle = { fontStyle: "italic" };
const codeStyle = { fontFamily: "Menlo" };
const underlineStyle = { textDecorationLine: "underline" };
const strikeStyle = { textDecorationLine: "line-through" };
const baseStyles = StyleSheet.create({
b: boldStyle,
strong: boldStyle,
i: italicStyle,
em: italicStyle,
pre: codeStyle,
u: underlineStyle,
strike: strikeStyle,
code: codeStyle,
a: {
fontWeight: "500",
color: "#007AFF"
}
});
class HtmlView extends Component {
constructor() {
super();
this.state = {
element: null
};
}
componentDidMount() {
this.mounted = true;
this.startHtmlRender(this.props.value);
}
componentWillReceiveProps(nextProps) {
if (this.props.value !== nextProps.value) {
this.startHtmlRender(nextProps.value);
}
}
componentWillUnmount() {
this.mounted = false;
}
startHtmlRender(value) {
if (!value) {
this.setState({ element: null });
}
const opts = {
linkHandler: this.props.onLinkPress,
styles: Object.assign({}, baseStyles, this.props.theme),
customRenderer: this.props.renderNode,
stylesheet: this.props.stylesheet || {}
};
htmlToElement(value, opts, (err, element) => {
if (err) {
this.props.onError(err);
}
if (this.mounted) {
this.setState({ element });
}
});
}
render() {
if (this.state.element) {
return (
<Text
style={this.props.stylesheet}
children={this.state.element}
{...this.props}
/>
);
}
return <Text style={this.props.stylesheet} {...this.props} />;
}
}
HtmlView.defaultProps = {
onLinkPress: url => Linking.openURL(url),
onError: console.error.bind(console)
};
export default HtmlView;