forked from jsdf/react-native-htmlview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HTMLView.js
98 lines (84 loc) · 2.21 KB
/
HTMLView.js
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
92
93
94
95
96
97
98
import React, {Component, PropTypes} from 'react';
import htmlToElement from './htmlToElement';
import {Linking, StyleSheet, View, ViewPropTypes} from 'react-native';
const boldStyle = {fontWeight: '500'};
const italicStyle = {fontStyle: 'italic'};
const codeStyle = {fontFamily: 'Menlo'};
const baseStyles = StyleSheet.create({
b: boldStyle,
strong: boldStyle,
i: italicStyle,
em: italicStyle,
pre: codeStyle,
code: codeStyle,
a: {
fontWeight: '500',
color: '#007AFF',
},
h1: {fontWeight: '500', fontSize: 36},
h2: {fontWeight: '500', fontSize: 30},
h3: {fontWeight: '500', fontSize: 24},
h4: {fontWeight: '500', fontSize: 18},
h5: {fontWeight: '500', fontSize: 14},
h6: {fontWeight: '500', fontSize: 12},
});
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 = {
addLineBreaks: this.props.addLineBreaks,
linkHandler: this.props.onLinkPress,
styles: Object.assign({}, baseStyles, this.props.stylesheet),
customRenderer: this.props.renderNode,
};
htmlToElement(value, opts, (err, element) => {
if (err) {
this.props.onError(err);
}
if (this.mounted) {
this.setState({element});
}
});
}
render() {
if (this.state.element) {
return <View children={this.state.element} style={this.props.style} />;
}
return <View style={this.props.style} />;
}
}
HtmlView.propTypes = {
addLineBreaks: PropTypes.bool,
value: PropTypes.string,
stylesheet: PropTypes.object,
style: ViewPropTypes.style,
onLinkPress: PropTypes.func,
onError: PropTypes.func,
renderNode: PropTypes.func,
};
HtmlView.defaultProps = {
addLineBreaks: true,
onLinkPress: url => Linking.openURL(url),
onError: console.error.bind(console),
};
export default HtmlView;